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 ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.