Cover by Cameron Newham, JP Vossen, Carl Albing

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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
	catemail_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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required