Sending email with Mail::Mailer

The Mail::Mailer module can be used to send email from a CGI script (or, for that matter, any script). Like Text::Template, it is an Object Oriented module. The object it creates is a "mailer" object, which can be opened and then printed to as if it were a filehandle.

#!/usr/bin/perl -w

use strict;
use Mail::Mailer;

my $mailer = new Mail::Mailer;

# the open() method takes a hash reference with keys which are mail
# header names and values which are the values of those mail headers

$mailer->open( {
        From    =>      'fred@example.com',
        To      =>      'barney@example.com',
        Subject =>      'Web form submission'
} );

# we can print to $mailer just as we would print to STDOUT or any 
# other file handle...

print $mailer qq(
Dear Barney,

Here is a form submission from your website:

Name:           $name
Email:          $email
Comments:       $comments

Love, Fred.

);

$mailer->close();

You can also open a pipe to sendmail directly, but doing this correctly can be difficult. This is why we recommend Mail::Mailer to avoid re-inventing the wheel.

Exercises

  1. Create an HTML form with fields for name, email and comment

  2. Use the above script (cgi-bin/mail.cgi) to mail the results of the script to yourself. You will need to edit it to work fully:

    • Use CGI.pm to pick up the parameters

    • Change the email address to your own address

    • Print out a "thank you" page once the form has been submitted -- don't forget the Content-type header