Heiner's SHELLdorado
Sending files as mail attachments
SHELLdorado - your UNIX shell scripting resource
HomeGood Shell Coding PracticesExample Shell ScriptsShell Scripting LinksShell Scripting Tips+TricksShell Scripting Articles

Articles Home
  Sending e-mail using shell scripts
  File attachments with "uuencode"
  File attachments with MIME
  References

Abstract

This article shows how to send e-mails from a shell script, including file attachments. It lists different ways (uuencode, MIME), and explains the advantages and disadvantages of each.

The appendix contains a shell script "sendfile" that simplifies sending MIME file attachments using scripts.


Sending e-mail using shell scripts

Most script programmers already know how easy it is to send e-mail from within shell scripts. A simple invocation of the mail program with the recipient for a command line argument will send all data read from standard input:
    $ mail root < /tmp/db_reorg.log
    $ echo "Coming home for dinner!" | mail sylvia@home.com
The "mail" command accepts additional command line parameters, e.g.
-s subject Use subject for the e-mail title
-c address Send copy of the mail to the specified address
-b address Send blind carbon copy to specified address

Some common usage examples:

    Send a log file to the system administrator:
    # mail -s "Reorganization completed" root < db_reorg.log

    Send mail to "mark" with copy to "john":
    $ echo "John's coming with us" |
        mail -c john -s "Join us watching Star Wars" mark
Portability

Note that not all mail commands have an "-s" option to specify a mail subject. Sometimes an extended version of the mail command is available with the name "mailx", e.g. /usr/ucb/mailx, or "Mail" (with a capital "M").

But how can we "attach" a file to a mail? We know that newer mail readers like Mozilla, Netscape Messenger or Microsoft Exchange have a way of displaying file attachments, e.g. images, ZIP files or audio files. How can we send some mail text (e.g. "See this picture of me surfing!") together with a binary file (e.g. "surfing.jpeg")?

The next chapter describes the traditional approach using "uuencode".

Top of document


File attachments with "uuencode"

Sending binary files does not work well for the Internet. We could send a binary file "surfing.jpeg" using this command:
mail -s "picture of me surfing" sylvia@home.com < surfing.jpeg
but chances are high that the image will be unusable the time it arrives at the recipient.

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" ("UNIX to UNIX encoding"), the program to decode the data is called "uudecode".

The simplest way to send a file as a mail attachment is shown by the following example:

    $ uuencode surfing.jpeg surfing.jpeg | mail sylvia@home.com

That's all! If Sylvia uses a current mail reader like Mozilla, Netscape Messenger or Microsoft Exchange, she will see a mail containing just one file attachment: the file "surfing.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.

This way we can include normal text, too:

    $ (cat mailtext; uuencode surfing.jpeg surfing.jpeg) |
        mail sylvia@home.com

Note: The file name "surfing.jpeg" again appears twice on the uuencode command line: the first time to specify the input file name, the second time for the remote extraction file name.

The first "cat" will prepend the contents of the file "mailtext" to the "uuencode"ed data of the image "surfing.jpeg". Both commands are executed within a sub shell, to combine the output of both commands to one output stream redirected to the "mail" command.

This method of sending file attachments works fairly well, but still has some shortcomings:

  • Many user agents cannot directly decode this kind of file attachments, e.g. "Eudora". Some mail agents explicitly require the decoding of the mail using the program "uudecode"
  • The "uuencode" encoding is not standardized. Text encoded on one system may not be decoded correctly by the recipient's system
        [the content of the mail message was saved to
        the file "mail.uue"]
        $ uudecode mail.uue
        The file "surfing.jpeg" was written to the current directory

The next method does not have this disadvantages. It works with most (newer) mail user agents and uses the "Multipurpose Internet Mail Extensions" (MIME).

Top of document


File attachments with MIME

The MIME Standard ("Multipurpose Internet Mail Extensions") defines an impressive list of new features for e-mail messages, e.g.
  • arbitrary file attachments, e.g. images, audio files
  • more than one file attachment per mail
  • multi-part messages

Other features are non-ASCII character sets for message bodies and message headers.

But how can shell programmers use these features effectively?

At first there has to be a command-line driven program to send MIME mails. There are some MIME packages available free of charge, the most common being

But check your local system before downloading one of these packages, many UNIX systems (e.g. Linux) come with one or more of them pre-installed.

mutt is an interactive, text-oriented e-mail client. Not very useful for usage in a script, one might think. But on closer view the program turns out to provide an easy way to send e-mails with file attachments. Have a look at the following example:

    $ mutt -s "Birthday celebration" -a citymap.jpg all@friends.org \
    	< invitation.txt
This command shows how to specify four important parts of an e-mail:
  • The recipient ("all@friends.org")
  • The main body of the e-mail (read from standard input, here redirected from the file "invitation.txt")
  • An attachment (with option -a)
  • A subject line (option -s)
The interesting part is the option -a, which allows us to send an attachment (in this case a picture of a city map). We could have added more attachments by using multiple -a options.

mutt always reads a text from standard input that will become the main body of the e-mail, the text before the attachment. If the mail should consist of attachments only, we can either specify /dev/null as the file to read, e.g.

    $ mutt -a syslogs.tar.gz admin@domain.org < /dev/null
or use an empty line as the mail body:
    $ echo | mutt -a syslogs.tar.gz admin@domain.org
mutt does some work behind the scenes, e.g. it's looking at the file extensions of the attachments, and selects an appropriate MIME type for each. This works reasonably well (depending on the configuration of the system in general and mutt in particular), but if more control about MIME types and the sending of the e-mail is required, the next package may be more appropriate.

The remainder of this chapter will use programs of the MetaMail package for the examples. Don't worry if the command lines seem somewhat cryptic, at the end of this article we will present a script simplifying the sending of mail attachments.

MetaMail provides two programs to send mail: mailto and metasend. We will use the second one for scripting, because it can be used non-interactively. The most interesting command line arguments of metasend are listed in the following table [refer to metasend(1) for a complete list].

-b batch (non-interactive) mode
-c cc CC address (for copy of the mail)
-f filename Name of file to attach
-m MIME-type MIME content type, e.g. "text/plain" or "application/octet-stream"
-s subject Title (subject) of the mail message
-t to Recipient's address
-n Next file attachment (needed for multiple file attachments)
-D description Description of the file content
-o outputfile Name of an output file. If the -t option is given, the mail is sent directly to the addressee

This new knowledge enables us to send an audio file using "metasend":

    $ metasend -b -t john@friends.org -s "Hear our son!" \
    	-m audio/basic -f crying.au

This invocation of "metasend" sends a mail to "john@friends.org" (option -t) with the subject "Hear our son!" (option -s), without prompting for further arguments (option -b). Without the "-b" argument, the command would have asked for addresses to send "carbon copies" to. The file to attach is called "crying.au", and the file type is "audio/basic".

The file type (or "MIME-type") "audio/basic" gives the recipient's mail reader a hint on the contents of the file attachment. Some contents may be displayed directly (e.g. "text/plain", "image/gif"), for others the mail reader may call external programs to present the contents (e.g. "application/postscript", "audio/wav"). The relation between MIME content type and external program to call often is established using a file called "mailcap" (see mailcap(4), if available on your system). Mozilla or Netscape's Communicator allows to specify "helper applications" that are invoked depending on the MIME type.

An annoying property of "metasend" is the need to specify the MIME type for each file. The script sendfile simplifies this. The following example sends two files, "cover.gif" and "contents.ps":

    $ sendfile editor@somewhere.com cover.gif contents.ps
    [Text to appear before the attachments, EOF to end]
    Hello John, you'll find a table of contents attached to
    this e-mail.
    ^D

The script is easier to use because it determines the MIME type of the specified files by examining their file name extension, e.g. ".gif" or ".ps".

The command used to determine the MIME type is getmimetype.

Top of document

References

  • Scripts to send file attachments using "metamail": sendfile, getmimetype
  • The Mutt main site is http://www.mutt.org/. The program is available for multiple UNIX dialects, and for Microsoft Windows.
  • MetaMail download (from the author Nathaniel S. Borenstein): ftp://ftp.research.telcordia.com/pub/nsb/)
  • Tucker, Kyle: Sending email with attachments on UNIX systems
    A good article describing the usage of other UNIX mail programs, e.g. mutt, elm, pine, and Z-Mail
  • mpack download (from the author John G. Myers): ftp://ftp.andrew.cmu.edu/pub/mpack/
  • Freed, N.; Borenstein, N.: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies (RFC 2045)
    Internet Engineering Task Force Working Group, 1996.
    Describes among other things the MIME Header fields, and the "Quoted Printable" and "Base64" encoding.
  • Freed, N.; Borenstein, N.: Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types (RFC 2046)
    Internet Engineering Task Force Working Group, 1996.
    Defines basic media types (e.g. "image/gif"), and handles multipart messages.
  • Freed, N.; Borenstein, N.: Multipurpose Internet Mail Extensions (MIME) Part Three: Message Header Extensions for Non-ASCII Text (RFC 2047)
    Internet Engineering Task Force Working Group, 1996.
    Describes the "quoted printable" encoding of mail headers.
  • Freed, N.; Klensin, J.; Postel, J.: Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures (RFC 2048)
    Internet Engineering Task Force Working Group, 1996.
    Describes the prerequisites needed for registering new MIME media types and content transfer encodings.
   
Copyright © 1998-2014 Heiner Steven (heiner.steven@shelldorado.com)