Emailing from a Perl Program

There are two basic approaches for sending email from inside a perl program. The first, which is appropriate on any system which runs the sendmail program, is to use the system function to compose your message and pass it along to sendmail. On most UNIX systems, this should work without any problems.

Here's a very simple example of how to use sendmail from inside a perl program:

$sendmailcmd = "/usr/lib/sendmail -oi -t -odq";
$mailto = "recipient@somehost.com";
$mailfrom = "youremail@yourhost.com";
$subject = "Test of sendmail";
$msg = "Here is a message.\nIt was sent from perl\n";

open(SENDMAIL, "|$sendmailcmd") || die "cannot fork to sendmail $!\n";

print SENDMAIL <<EOF;
From: $mailfrom
To: $mailto
Subject: $subject

$msg
EOF

close(SENDMAIL) || warn "sendmail didn't close";

Additional headers (bc, cc, Reply-to, can be added after Subject; there should be at least one completely blank (no characters) line after the headers are completed.

If sendmail is not available, but you know of a host which will provide SMTP (simple mail transport protocol) services, you can use the Net::SMTP module to send your request to the host which provides SMTP services. You can't just pick a host at random, because most SMTP servers place restrictions on who can use them, but if it's possible to send mail from a particular computer, there should be a host to provide SMTP services.

Here's a simple program which uses Net::SMTP to send an email:

use Net::SMTP;

$smtpServer = "smtp.yournet.com";
$mailto = "recipient@somehost.com";
$mailfrom = "youremail@yourhost.com"
$subject = "Test of sendmail";
$msg = "Here is a message.\nIt was sent from perl\n";

$s = new Net::SMTP $smtpServer || die "Couldn't connect to $smtpServer";

$s->mail($mailfrom);
$s->to($mailto);

$s->data();
$s->datasend("Subject: $subject");
$s->datasend("\n");
$s->datasend($msg);
$s->dataend();

$s->quit();

Additional headers can be added through the datasend method. The single newline sent after the subject line is required to signal to the SMTP server that the headers are finished.

For more information on Net::SMTP, see Emmie Lewis' article at about.com.
Phil Spector
Last modified: Fri Oct 10 14:20:54 PDT 2003