Wednesday, 27 February 2013

Useful trick for sending HTML email

Sometimes you want to send an email as HTML from a script or from script output anyhow.  There's a couple ways to get the HTML page to the recipient.  You can attach the HTML page or you can set your Content-Type to HTML.  In my case, we're looking at scraping a web page as a cron job and sending it to some recipient(s) - the mainstay is:

curl 'http://server/web/page.html'
Attaching an HTML file is safe, but recipients may not like "opening attachments".  For HTML email, the security risk is the same, but there's a perception that "opening attachments is bad" which I wouldn't discourage as a general practice.  Rambling aside, "uuencode" will encode an attachment, any attachment, and can be used in general (word doc, zip file, etc).

curl 'http://server/web/page.html' | uuencode attachmentname.html

The other way is to set the content type to HTML and the HTML becomes the body of the email.  On some operating systems, namely Debian and Ubuntu, the mail / mailx command can add a header with the -a switch.  This is pretty simple.

curl 'http://server/web/page.html' | mail -a "Content-Type: text/html" -s "An HTML email" some-recipient@example.com

However if you are on a Red Hat / Fedora / CentOS system, your mail command does not support the -a switch.  Here you can use mutt and the mutt method will work in general.

curl 'http://server/web/page.html' | mutt -e "my_hdr Content-Type:text/html" -e "set charset=\"utf-8\"" -s "An HTML emailsome-recipient@example.com

There you have it.  Personally not a fan of HTML email (since it opens the doors to a lot of malware attacks), but if you've got to generate HTML email, using standard tools instead of writing your own perl script to wrap the scraping of a web page and generating an email is going to be much simpler.

Thanks to the "telinit q" blog for helping with this answer.  http://blog.telinitq.com/?p=137

Popular Posts