Sending Email from Your Script
Problem
You’d like your script to be able to send email, optionally with attachments.
Solution
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" recipient1@example.com recipient2@example. com
or:
# Attachment only $ uuencode /path/to/attachment_file attachment_name | mail -s "Message Subject" recipient1@example.com recipient2@example.com
or:
# Attachment and body $ (cat email_body ; uuencode /path/to/attachment_file attachment_name) | mail -s "Message Subject" recipient1@example.com recipient2@example.com
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 the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.