Wednesday, 28 May 2014

Send HTML Format Email From Linux

The following script is very useful for sending HTML formatted emails from Linux.

Simply pipe the HTML into it, and the script adds the necessary header information before sending it on it's way. The script assumes that sendmail is installed and configured.

I wrote the original version of this script back in 2006, and it has proved so useful - for presenting daily system reports with warnings in red, for example - that I have used versions of it in most companies that I have done work for ever since.

#!/usr/bin/bash
##################################################################
#
# htmmail
#
# Purpose: To send html formatted emails
#
# Syntax: htmmail [-s Subject] address [address] [address...]
#
# Subject The subject of the email
# address The email address of the intended recipient
#
# The content of the email may be included by piping it
# into the htmmail command.
#
# Author: Douglas Milne
# Date: 27th May 2014
#
##################################################################
#
# Version 1.0 Initial Release
#
##################################################################

# Get options
# s flag argument is the subject of the email
#
while getopts s: value
do
case $value in
s) SUBJECT=$2
;;
\?) echo "$0: unknown option $OPTARG"
;;
esac
done

shift $(expr $OPTIND - 1)

# Remaining arguments are email addresses to send the email
TO=$*

# Set up email header, including content type field
# signifying html format.
# To and Subject as specified above

/usr/lib/sendmail -t << EOF
mime-version: 1.0
content-type: text/html; charset="iso-8859-1"
To: $TO
Subject: $SUBJECT

$(cat)

EOF