Pipes | Streams  «Prev  Next»

Lesson 6Sending email in Perl
ObjectiveExperiment with sending email from Perl

Experiment with sending email from Perl

Now that you understand how pipes work, you can start building the second of our course projects, the email program.
The simplest way to send mail from a Perl program is to pipe the mail to another program that is designed to send email.
On Unix systems, that program is usually called sendmail. On other systems, it may be called something else and work differently than sendmail. However, since most Internet mail has traditionally been sent via the sendmail program on Unix systems and it is the most common mail transfer program available, we will use it for this example.
Windows and Linux users may want to try using softmail for the purpose of the next several lessons.

#!/usr/bin/perl -w

$sendmail = "/usr/lib/sendmail -t";
$from     = "yourname\@yourdomain.com";
$to       = "whoever\@wherever.net";
$subject  = "here's a subject!";

open(MAIL, "|$sendmail");

print MAIL <<MESSAGE;
From: $from
To: $to
Subject: $subject

Now is the time for all good...
oh, forget it!

MESSAGE
close MAIL;

All the parameters for the mail, including the command line to use for the piped call to sendmail, are put in variables at the top. This should make it easy for you to customize the program to work on your system.
The open() function simply opens a pipe to the mail transfer program, then a normal call to the print() function sends the mail message to the MAIL stream. The first part of the message are the mail headers, which must be separated from the body of the message by a blank line.
In the next lesson, we will build a Web form that sends email. This is a handy device for letting your users communicate with you, and it is far more flexible than the standard mailto: URL.