Sending email with Perl in 2010

Example of how you should send email in 2010 with Perl.

#!/usr/bin/perl -w
use strict;

use Email::Sender::Simple qw(sendmail);
use Email::Simple;
use Email::Simple::Creator;

my $email = Email::Simple->create(
    header => [
        To      => '"Peter Foo" <foo@example.com>',
        From    => '"Peter Bar" <bar@example.org>',
        Subject => "What's up",
    ],
    body => "Hey, how are you doing?",
);

sendmail($email);

You can see that this is simple enough. First you create an Email::Simple object. This object will format the message that wil be sent.

After that sendmail will send this message using it's default transport.

The nice thing about using these modules is that you can, while testing, replace the default transport with testing modules.

use Test::More;
BEGIN { $ENV{EMAIL_SENDER_TRANSPORT} = 'Test' }
use YourModule;

YourModule->run;
my @deliveries = Email::Sender::Simple->default_transport->deliveries;
is(@deliveries, 1);

This way you can check how many emails were send using in the code your testing. By picking apart @deliviries you can check out the text of the emails that were send. See Email::Sender::Transport::Test for more information about this.

Welcome

My name is Peter Stuifzand. You're reading my personal website.

Profiles