Send HTML email from the command line

Fri 24 October 2014
By alex

Sometimes there's nothing better than receiving an email from some long forgotten cronjob and having it formatted in nice readable HTML. Well it's alot tougher than it should be to make that happen.

The only way I've found to accomplish this is to inject 'Content-Type' headers into the email when it's being sent. And conviently, not all mail clients do this the same way.

mailx from bsd-mailx provides the most consistent way of adding arbitrary email headers to outgoing mail. You just have to be sure it's the only client installed.

Install the goods:

sudo apt-get purge heirloom-mailx
sudo apt-get install bsd-mailx

To craft the email:

mailx -a 'Content-Type: text/html; charset="utf-8"' -a 'From: [email protected]' -s 'Subject' '[email protected]' 

Now put it to work:

python ~/generate-report.py && cat /tmp/report.html | mailx -a 'Content-Type: text/html; charset="utf-8"' -a 'From: [email protected]' -s 'Subject' '[email protected]'