HOWTO Send email from shell scripts

HOWTO Send email from shell scripts

From Consultancy.EdVoncken.NET

Jump to: navigation, search

Contents

[edit] Problem

You wish to send email, possibly with attachments.

[edit] Solution

On Unix, email can be sent using standard mail functionality. Pick whichever form you like best:

 echo "This is the message text" | mail -s "This is the subject line" recipient@example.com
 cat message.txt | mail -s "This is the subject line" recipient@example.com
 mail -s "This is the subject line" recipient@example.com <message.txt

Attachments need to be converted to ASCII format before they can be sent. Two popular formats are:

uuencode
this format was developed during the UUCP era (Unix to Unix CoPy)
MIME
this is the modern format, also used in web browsers

[edit] uuencode

Sending an image (image.jpg):

 uuencode image.jpg image.jpg | mail -s "This is the subject line" recipient@example.com

If you need to send some text as well as the image (backslashes indicate a line continuation, commands are one long line):

 ( echo "This is the message text"; uuencode image.jpg image.jpg )  \
           | mail -s "This is the subject line" recipient@example.com
 
 ( cat message.txt; uuencode image.jpg image.jpg )  \
           | mail -s "This is the subject line" recipient@example.com

[edit] MIME

There are several options available. Here, I will use the Mutt email client. Again, pick whichever form you like best:

 echo "This is the message text" | mutt -s "This is the subject line" -a image.jpg recipient@example.com
 
 cat message.txt | mutt -s "This is the subject line" -a image.jpg recipient@example.com
 
 mutt -s "This is the subject line" -a image.jpg recipient@example.com <message.txt