Sending Email from Your Script


You’d like your script to be able to send email, optionally with attachments.


These solutions depend on a compatible mailer such as mail, mailx, or mailto, an Message Transfer Agent (MTA) being installed and running, and proper configuration of your email environment. Unfortunately, you can’t always count on all of that, so these solutions must be well tested in your intended environment.

The first way to send mail from your script is to write some code to generate and send a message, as follows:

# Simple
cat email_body | mail -s "Message subject" recipient2@example.


# Attachment only
$ uuencode /path/to/attachment_file attachment_name | mail -s "Message Subject"


# Attachment and body
$ (cat email_body ; uuencode /path/to/attachment_file attachment_name) | mail -s
"Message Subject"

In practice, it’s not always that easy. For one thing, while uuencode will probably be there, mail and friends may or may not, or their capabilities may vary. In some cases mail and mailx are even the same program, hard-or soft-linked together. In production, you will want to use some abstraction to allow for portability. For example, mail works on Linux and the BSDs, but mailx is required for Solaris since its mail lacks support for -s. mailx works on some Linux distributions (e.g., Debian), but not others (e.g., Red Hat). We’re choosing ...

Get bash Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.