How to attach a file using mail command on Linux? [duplicate]
Asked Answered
S

13

61

I'm on a server running a Linux shell. I need to mail a simple file to a recipient. How to do this, prefereably using only the mail command?

UPDATE: got a good solution, using mutt instead:

$ echo | mutt -a syslogs.tar.gz [email protected]
Slipover answered 23/5, 2009 at 22:5 Comment(1)
The duplicate has an answer of mine which attempts to sort out and clarify the several incompatible versions of mail/mailx to hopefully make some sense of the multiple conflicting answers here and elsewhere.Cabotage
F
52

Example using uuencode:

uuencode surfing.jpeg surfing.jpeg | mail [email protected]

and reference article:

http://www.shelldorado.com/articles/mailattachments.html

Note:

you may apt install sharutils to have uuencode command

Finfoot answered 23/5, 2009 at 22:9 Comment(8)
Commentary on archives.neohapsis.com/archives/postfix/2008-10/0422.html ?Pye
Is uuencode a "default" GNU tool? My box doesn't seem to have it.Slipover
The reference article was really useful! Thanks!Slipover
@Seiti: uuencode is a part of sharutils, and it is GNU software. Ubuntu package is called sharutils, too. gnu.org/software/sharutilsDeandreadeane
This works only for recipients which allow uuencoded attachmentsMozzetta
On ubuntu, the following will install uuencode and mail (respectively): sudo apt-get install sharutils; sudo apt-get install mailutilsGreeley
This is a good workaround for an ecosystem which is stuck in the early 1990s but the preferred solution in the modern world is to switch to MIME. The solution with mutt does that nicely and reasonably portably.Cabotage
If you wish to have an attachment AND text in the body, here is a similar answer: https://mcmap.net/q/102735/-sending-simple-message-body-file-attachment-using-linux-mailx-duplicateGranular
C
23

mail on every version of modern Linux that I've tried can do it. No need for other software:

matiu@matiu-laptop:~$ mail -a doc.jpg [email protected]
Subject: testing

This is a test
EOT

ctrl+d when you're done typing.

Cavesson answered 29/5, 2014 at 15:46 Comment(7)
Not really accurate. There are versions of mail which support this, but they are certainly not "plain old mail" but rather, some modernized version or variant. It would help if you specify which version you are using, on which platform.Cabotage
This is on ubuntu 14.04 using Heirloom mailx version 12.5 6/20/10. From memory, it also works on centos 6, ubuntu 12.04 and centos 7.Cavesson
i was able to do this in interactive mode, I was wondering if there is a script version of this?Armorer
To make it not require user interaction: echo This is a test | mail -a doc.jpg -s "testing" [email protected]Cavesson
Worked with RHEL6.8 mail ver: 12.4 7/29/08Sympathize
The mailutils version of mail uses -A for attachments (GNU Mailutils 2.99.99 on Ubuntu 16.04 Xenial Server)Hahn
#17859 now has an overview of different mail heritages which II had originally posted as an answer to this question.Cabotage
S
22
$ echo | mutt -a syslogs.tar.gz [email protected]

But it uses mutt, not mail (or mailx).

Slipover answered 23/5, 2009 at 22:49 Comment(2)
Did not QUITE work for me. Order of arguments was different. What worked was: echo | mutt [email protected] -a syslogs.tar.gz. I am using mutt version 1.5.20.Tahmosh
It works for me to send log from unix to mail server. ThanksWayfarer
K
13

mailx might help as well. From the mailx man page:

-a file
     Attach the given file to the message.

Pretty easy, right?

Keys answered 23/5, 2009 at 22:24 Comment(3)
note that this is not the mailx in Ubuntu. Using that one, -a means Specify additional header fields on the command line such as "X-Loop: foo@bar" etc. You have to use quotes if the string contains spaces. This argument may be specified more than once, the headers will then be concatenated.Deandreadeane
My mailx doesn't support -a (package mailx-8.1.1-44.2.2 on CentOS)Sugden
Mine doesn't support -a either (OS X 10.7.5)Mozzetta
H
12

My answer needs base64 in addition to mail, but some uuencode versions can also do base64 with -m, or you can forget about mime and use the plain uuencode output...

   [email protected]
   [email protected]
   SUBJECT="Auto emailed"
   MIME="application/x-gzip"  # Adjust this to the proper mime-type of file
   FILE=somefile.tar.gz
   ENCODING=base64  
   boundary="---my-unlikely-text-for-mime-boundary---$$--" 

   (cat <<EOF
    From: $FROM
    To: $REPORT_DEST
    Subject: $SUBJECT
    Date: $(date +"%a, %b %e %Y %T %z")
    Mime-Version: 1.0
    Content-Type: multipart/mixed; boundary="$boundary"
    Content-Disposition: inline

    --$boundary
    Content-Type: text/plain; charset=us-ascii
    Content-Disposition: inline

    This email has attached the file

    --$boundary
    Content-Type: $MIME;name="$FILE"
    Content-Disposition: attachment;filename="$FILE"
    Content-Transfer-Encoding: $ENCODING

    EOF
    base64 $FILE
    echo ""
    echo "--$boundary" ) | mail
Heffernan answered 23/5, 2009 at 22:21 Comment(6)
For some reason when using mutt, encrypted attachments would grow by 400-500% when encoded which basically limited me to ~2MB attachments. So I had to build the email from scratch with a base64 encoded attachment using this method, except I'm sure you meant to pipe it to sendmail -t instead.Slovene
Nice answer - I like the cat append part.Caucasus
This is nice if you don't have access to proper MIME tools, but piecing together the MIME structure by hand gets tired fast. If you have more than a one-off need, you probably want to find a tool which encapsulates these steps for you.Cabotage
And that's assuming your mail doesn't choke on MIME input, but you can just switch to | sendmail -oi -t at the end of the pipeline in that case; you don't need any of the features that the mail wrapper offers you any longer at this point.Cabotage
The final line should have echo "--$boundary--" before the closing parenthesis, with two dashes at the end to mark this as the final, closing boundary.Cabotage
The Content-Disposition: inline is RFC-correct but apparently problematic for Yahoo (but then what isn't); it's perfectly optional anyway, so maybe just take it out if that's a consideration. See also #48436717Cabotage
P
7
mailx -a /path/to/file email@address

You might go into interactive mode (it will prompt you with "Subject: " and then a blank line), enter a subject, then enter a body and hit Ctrl+D (EOT) to finish.

Paraboloid answered 25/4, 2012 at 22:34 Comment(3)
On Mac 10.7 I get an error doing this. mailx: illegal option -- aThaumaturgy
that's because OSX doesn't have lots of the modern updated CLI utilities like linux has. use homebrew or macports to install coreutilsCollator
@Collator mailx is not part of GNU coreutils. You can probably find a version of mailx for OSX which supports this usage, but without a link to one, this isn't really helpful at all. There are multiple versions, many of which do not support this usage.Cabotage
S
4
mpack -a \
    -s"Hey: might this serve as your report?" \
    -m 0 -c application/x-tar-gz \
    survey_results.tar.gz \
    [email protected]

mpack and munpack work together with metamail to extend mailx and make it useful with modern email cluttered with HTML markup and attachments.

Those four packages taken together will permit you to handle any email you could in a GUI mail client.

Sparkman answered 18/10, 2011 at 18:0 Comment(2)
This worked for me, nothing else seemed to work on Ubuntu 12.04Skipp
Unfortunately, the metamail package which contined these utilities has been abandoned and is now very hard to find. You are probably better off with a modern MIME client anyway; these old utilities were provided as a baseline demonstration when MIME was new, but they were never very versatile or easy to use.Cabotage
E
2

Using ubuntu 10.4, this is how the mutt solution is written

echo | mutt -a myfile.zip -- [email protected]

Excellency answered 23/9, 2013 at 8:28 Comment(1)
Same for mutt from HomebrewMozzetta
C
1

There are a lot of answers here using mutt or mailx or people saying mail doesn't support "-a"

First, Ubuntu 14.0.4 mail from mailutils supports this:

mail -A filename -s "subject" [email protected]

Second, I found that by using the "man mail" command and searching for "attach"

Contaminant answered 14/3, 2016 at 20:40 Comment(0)
G
1

The following is a decent solution across Unix/Linux installations, that does not rely on any unusual program features. This supports a multi-line message body, multiple attachments, and all the other typical features of mailx.

Unfortunately, it does not fit on a single line.

#!/bin/ksh

# Get the date stamp for temporary files
DT_STAMP=`date +'%C%y%m%d%H%M%S'`

# Create a multi-line body
echo "here you put the message body
which can be split across multiple lines!
woohoo!
" > body-${DT_STAMP}.mail

# Add several attachments
uuencode File1.pdf File1.pdf >  attachments-${DT_STAMP}.mail
uuencode File2.pdf File2.pdf >> attachments-${DT_STAMP}.mail

# Put everything together and send it off!
cat body-${DT_STAMP}.mail attachments-${DT_STAMP}.mail > out-${DT_STAMP}.mail
mailx -s "here you put the message subject" [email protected] < out-${DT_STAMP}.mail

# Clean up temporary files
rm body-${DT_STAMP}.mail
rm attachments-${DT_STAMP}.mail
rm out-${DT_STAMP}.mail
Granular answered 31/1, 2018 at 18:0 Comment(1)
I
0

With mailx you can do:

mailx -s "My Subject"  -a ./mail_att.csv -S [email protected]  [email protected] < ./mail_body.txt

This worked great on our GNU Linux servers, but unfortunately my dev environment is Mac OsX which only has a crummy old BSD version of mailx. Normally I use Coreutils to get better versions of unix commands than the Mac BSD ones, but mailx is not in Coreutils.

I found a solution from notpeter in an unrelated thread (https://serverfault.com/questions/196001/using-unix-mail-mailx-with-a-modern-mail-server-imap-instead-of-mbox-files) which was to download the Heirloom mailx OSX binary package from http://www.tramm.li/iWiki/HeirloomNotes.html. It has a more featured mailx which can handle the above command syntax.

(Apologies for poor cross linking linking or attribution, I'm new to the site.)

Infundibulum answered 5/8, 2015 at 22:47 Comment(0)
E
0

On Linux I would suggest,

# FILE_TO_BE_ATTACHED=abc.gz

uuencode abc.gz abc.gz > abc.gz.enc # This is optional, but good to have
                                    # to prevent binary file corruption.
                                    # also it make sure to get original 
                                    # file on other system, w/o worry of endianness

# Sending Mail, multiple attachments, and multiple receivers.
echo "Body Part of Mail" | mailx -s "Subject Line" -a attachment1 -a abc.gz.enc "[email protected] [email protected]"

Upon receiving mail attachment, if you have used uuencode, you would need uudecode

uudecode abc.gz.enc

# This will generate file as original with name as same as the 2nd argument for uuencode.

Erlandson answered 2/11, 2016 at 10:45 Comment(1)
If you have a mailx which supports -a for including MIME attachments, there is absolutely no need to separately uuencode them. Attaching will wrap the content in a suitable content transfer encoding like base64 if necessary -- this is in fact more portable and robust than uuencode, as well as decidedly a lot more usable.Cabotage
R
0

I use mailutils and the confusing part is that in order to attach a file you need to use the capital A parameter. below is an example.

echo 'here you put the message body' | mail -A syslogs.tar.gz [email protected]

If you want to know if your mail command is from mailutils just run "mail -V".

root@your-server:~$ mail -V
mail (GNU Mailutils) 2.99.98
Copyright (C) 2010 Free Software Foundation, inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Richerson answered 23/8, 2017 at 9:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.