Sending Mail

You can get Perl to send email in several ways. One method that you see frequently is opening a pipe to the sendmail command and sending data to it (shown in Listing 27.5). Another method is using the Mail::sendmail module (available through CPAN), which uses socket connections directly to send mail (as shown in Listing 27.6). The latter method is faster because it does not have to launch an external process. Note that sendmail must be running on your system for the Perl program in Listing 27.5 to work.

Listing 27.5. Sending Mail Using Sendmail

#!/usr/bin/perl open (MAIL, "| /usr/sbin/sendmail -t"); # Use -t to protect from users print MAIL <<EndMail;

To: dpitts\

From: rbowen\

Subject: Email notification


Sending email from Perl is easy! Rich

EndMail close MAIL;


Note that the @ sign in the email addresses must be escaped so that Perl does not try to evaluate an array of that name. That is, [email protected] will cause a problem, so you need to use dpitts\

The syntax used to print the mail message is called a here document. The syntax is as follows:

print <<EndText;


The EndText value must be identical at the beginning and at the end of the block, including any whitespace.

Listing 27.6. Sending Mail Using the Mail::Sendmail Module

#!/usr/bin/perl use Mail::Sendmail; %mail = ('To' => '[email protected]', 'From' => '[email protected]' 'Subject' => 'Email notification', 'Message' => 'Sending email from Perl is easy!',


Perl ignores the comma after the last element in the hash. It is convenient to leave it there; if you want to add items to the hash, you don't need to add the comma. This is purely a style decision.

Was this article helpful?

0 0

Post a comment