Creating & sending HTML email from a shell script


This is a shell script that sends email containing HTML formatting. It uses a here-document combined with cat and the - STDIN parameter, which is all piped to sendmail. It appears mandatory to use the cat and here-document for handling the message header info. Putting it into $HTML along with the message body does not work, sendmail reports that it cannot figure out who the message recipient is. Perhaps it is the semi-colon on the Content-Type line, and the here-document is the only way to handle it correctly; but that is just a guess.

#!/bin/sh MAILFROM='buzz.lightyear@starcommand.mil' MAILTO='peter@example.com' HTML=" <h2>An html email message from a shell script</h2> This part of the message is just normal text. You can include whatever <b>HTML markup</b> you like here as well. To send images, you will have to put the images on an http server and then include a link to the images. <p> <i>Didn't know you could do this, did you?!</i> " cat - <<EOF | sendmail -oi -t From: ${MAILFROM} To: ${MAILTO} Subject: HTML email from shell script Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit MIME-Version: 1.0 $HTML EOF

To include images in the email, post the images on a publicly accessible HTTP server, and then include a link to it in the message.

A prior form of this script read the HTML part from an external file. To use this, the cat command was slightly different:

cat - /path/to/htmlfile <<EOF | sendmail -oi -t

04/08/2009