Sending email from Perl

January 28, 2011

#include <long-time-no-blog.h>

I often need to send emails from Perl scripts and over the years I’ve tried all sorts of modules which are supposedly the current “best practice” but rarely do they get even close to living up to the hype. Recently, however, I came across this article which introduced me to the MIME::Lite::TT module which genuinely does seem to be very nice and easy to use. Here is a snippet of how I am using it in the Package Forge build daemons to send status messages:

    my $msg = MIME::Lite::TT->new(
        From        => $from,
        To          => $to,
        Cc          => $cc,
        Subject     => "PkgForge Report - $builder - $job",
        Template    => $template,
        TmplParams  => \%params,
    );

    $msg->send();

The templating is done with the Perl Template Toolkit (TT). Handily, the template parameter can be either a reference to a scalar (i.e. the text is embedded in the code) or a filename. Also TT can be configured to work in whatever way you require by passing in a reference to an options hash as well as the params hash reference.

Most of the power is in the MIME::Lite Perl module which can easily handle all types of attachments and can send mail by various different methods if local sendmail is not appropriate. I can’t immediately spot anything it cannot do to meet my needs, particularly when extended to include the TT templating support.