Send mails with attachments from command-line

Here we’ll shows you how to send e-mails with file attachments from shell prompt. We’ll list two different ways, using uuencode and Mutt.

Generally with the help of mail command, it’s easy to send mails in shell scripts, and we can easily specify some of key parameters like subject and recipients. Here’s an example:

$ echo "Coming home for dinner!" | mail -s "invitations from peter" bob@example.com

But there’s no parameters for attaching files. How can we send attachments by the command mail in shell prompt?

In a normal way, sending binary files does not work well, as chances are high that the binary files will be unusable when it arrives at the recipient. Here’s a brief description for the potential changes:

During mail delivery the mail is relayed from one mail delivery agent to the next, until it finally arrives at the recipient. Each delivery agent may transform the mail message, e.g. by stripping the 8th bit of each character, removing NUL bytes (ASCII code 0), converting the end-of-line character LF (“line-feed”, ASCII code 12) to a local representation (e.g. CR LF), or removing trailing space or TAB characters from each line.

Since only some characters are sure to arrive unmodified, the traditional solution is to encode the mail from binary format to a text format that is safe to transmit. The program used for this is called “uuencode”, the program to decode the data is called “uudecode”. If you’re not sure how to install this command, please check my former post on random password generating. Then we have a solution here:

$ uuencode myboy.jpeg myboy.jpeg | mail bob@example.com

If Bob uses a mail reader like Thunderbird or Microsoft Outlook Express, he’ll see a mail containing just one file attachment: the file “myboy.jpeg”. In the command above we had to specify the file name two times: the first name denotes the input file to be encoded, and the second name is the file name the recipient will see.

Then if you wanna include normal text, the command can be:

$ (cat mail-message; uuencode myboy.jpeg myboy.jpeg) |mail bob@example.com

The second way is to use Mutt.

Mutt is a pure MUA and cannot send e-mail without proper email server(the above command mail is also a MUA). You need a running mail server such as sendmail, postfix or exim4 to send out mails.

Since mutt is not installed by default, you need to install it first:

$ sudo apt-get install mutt  #Debian/Ubuntu etc.
$ sudo yum install mutt      #Fedora/RHEL/CentOS etc.
# pkg_add -v -r mutt         #FreeBSD

How do I send email attachments via mutt in shell prompt?
Use mutt command as follows to send an email with attachment:

$ mutt -s "Test mail via Mutt" -a /tmp/report.tar.gz bob@example.com < /tmp/message-body.mail

Leave a comment

Your email address will not be published. Required fields are marked *