O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sending Mail

Problem

You want your program to send mail. Some programs monitor system resources like disk space and notify appropriate people by mail when disk space becomes dangerously low. CGI script authors may not want their programs to report errors like “the database is down” to the user, preferring instead to send mail to the database administrator notifying them of the problem.

Solution

Use the CPAN module Mail::Mailer:

use Mail::Mailer;

$mailer = Mail::Mailer->new("sendmail");
$mailer->open({ From    => $from_address,
                To      => $to_address,
                Subject => $subject,
              })
    or die "Can't open: $!\n";
print $mailer $body;
$mailer->close();

Or, use the sendmail program directly:

open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
                    or die "Can't fork for sendmail: $!\n";
print SENDMAIL <<"EOF";
From: User Originating Mail <me\@host>
To: Final Destination <you\@otherhost>
Subject: A relevant subject line

Body of the message goes here, in as many lines as you like.
EOF
close(SENDMAIL)     or warn "sendmail didn't close nicely";

Discussion

You have three choices for sending mail from your program. You can use another program that users normally use to send mail, like Mail or mailx ; these are called MUAs or Mail User Agents. You can use a system-level mail program like sendmail ; this is an MTA, or Mail Transport Agent. Or you can connect to an SMTP (Simple Mail Transfer Protocol) server. Unfortunately, there’s no standard user-level mail program, sendmail doesn’t have a standard location, and SMTP isn’t ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required