Send an HTML file as email from the command line.
Posted by simonw on Mon 27 Jun 2005 at 20:48
Do you need to send an HTML email from a script or command line? Whilst there are many different ways of doing this using mail from the mailx package is one of the simplest.
HTML email maybe evil according to some, but the simple but effective visitors package for reporting against Apache logs (ideally logs in combined logfile format to get; referer, operating system, and browser stats), produces prettier reports in HTML than it does in ASCII.
Previously we'd used a Perl script to send HTML emails, but I couldn't be bothered to port this to the new server, and it is copyright my employer so technically not free software (if I asked I'm sure they would share), so I reread the manual page for the "mail" command from the mailx package - chaces are you've already got this installed upon your server.
"mail" supports many options including the "-a" option for adding extra headers to the email. That'll do the job of making the mails it sends HTML.
visitors -A -o html /var/log/apache2/access.log.1 > ~/access.stats mail -a "Content-type: text/html;" -s "Webstats" email@example.com < ~/access.stats rm ~/access.stats
Hopefully that is pretty self explanatory. This of course was placed in a little script (handling multiple websites with statistics emailed to different people), executed by the 'postrotate' section of /etc/logrotate.d/apache2.
(You can read more about how logrotate works).
This is in the school of quick and dirty solutions (no locking against running concurrently etc), but it exhibits one bug less that the solution using the aforementioned Perl script (which perhaps wisely, but unnecessarily truncates lines to conform to relevant email RFC), so I'm sticking with it till it breaks. I've filed a couple of bug reports against the "visitors" package, as it has a few issues we needed to sort when using it for our clients on busy websites, but for my own personal use the unaltered package is superb.
If you need to send binary files via email, check out the package "mpack", which works in a very similar fashion, but because it packs stuff, it expects (and demands?!) more restrictive "Content-type" declarations. And yes I know "mutt" will do all this and more, I suspect Emacs can as well ;).
(You might want to look at reading HTML Mail in Mutt)