Sending email with attachments on UNIX systems

This page outlines several methods of generating email messages from command line and shell scripts using both popular email processing tools such as metamail and mpack, and home grown scripts. Most of these methods use the MIME specification, as outlined in RFC 2045, RFC 2046, RFC 2047, RFC 2048 and RFC 2049.

Please send mail to me with any comments, suggestions, criticism or additions.

All of the below examples use the following shell variables. I use MIME type application/octet-stream just as an example. Actual type used will vary depending upon attachment file type. Remember, these are simple examples of the different tools available.

TXTFILE=/tmp/textfile		# A text message with a simple preface message
ATTFILE=/tmp/binary_file	# File to be attached and generally requiring encoding
SUBJECT="Your attachment"	# Change as needed
MAILTO=user@where.ever		# Ditto

Here is some Bourne shell code (taken out of a deliver enabled autoresponder) for creating email messages with multiple attachments of varying types. This script uses metamail's mmencode program for encoding and sendmail for sending.

Check out this far more advanced shell script written by Dave Wotton that does much more than my simple script. It uses a encoder called encdec that I am not familiar with but will soon address on this page. In the meantime, you could use mmencode mentioned previously for the encoding.

And here is some basic, fairly static Perl code using the MIME::Lite module to send an attachment along with a text note to a sender. This is almost verbatim from the modules man page and could use some tweaking to get it more useful but it certainly works as a "plugin" piece of code.

Here is a useful page by Heiner Steven with several examples of shell coding using metamail and mpack in particular.

For an excellent guide to creating proper text files and for the formatting of your message if you write your own script, please see Keith Moore's style guide.