Sending E-mail with Perl

Buggy Unportable Unscalable Error Prone Method | Portable Scalable Method | Message Content

Buggy Unportable Unscalable Error Prone Method

Repeated far too often in code, despite flaws and limitations. Do not use!

open SENDMAIL, "|/usr/sbin/sendmail -t"
or die "$0: fatal: could not open sendmail: $!\n";
print SENDMAIL "To: user\@example.org\n";
print SENDMAIL "Subject: message\n\n";
print SENDMAIL "Message body\n";
close SENDMAIL;

Problems include:

Portable Scalable Method

Among the many Perl modules available on Comprehensive Perl Archive Network (CPAN) for sending e-mail, I favor MIME::Lite. Easy to use, easy to attach new content, and easy to send the message elsewhere for debugging.

use MIME::Lite;
my $message = MIME::Lite->new(
To => 'user@example.org',
Subject => 'message',
Data => 'Message body'
);
$message->send();

Message Content

Never build up a message into a scalar, then print the scalar. HTML errors become difficult and time consuming to debug in longer messages, and extending or reformatting the look of the message is nearly impossible.

my $message_body = '<html></body>';
$message_body .= '<B>This is as ugly as it looks</B';
if ($printer_on_fire) {
$message_body .= "<p>More <a href=\"ugh\">horrors</a>";
}

Instead, template the message with HTML::Template or similar module. This abstracts the data properly away from the content. At the very least, stop backslashing doublequotes in doublequoted strings:

my $ugly = "<a href=\"$url\">$link_text</a>";
my $link = qq{<a href="$url">$link_text</a>};