CGI and Perl

Formatting the Mail Text

The last thing you need is the function that sends the e-mail. There is an existing Perl module for sending mail, called Mail::Send. You can use this library to make your script simpler. The Mail::Send module provides methods to set the destination address, subject, and so on, and then open a file handle to which you can write the body of the mail message. Given that this module does all this for you, all you need to do is decide on the wording for the message. The function used to send the e-mail notification looks like Listing 7.14.

Listing 7.14. Subroutine for sending e-mail notification.

use Mail::Send;
 sub notifyOwner {
    my($licensePlate,$notifier)=@_;
    my(%info)=&findLicensePlate($licensePlate);
    if (defined($info{`email'})) {
 $msg = new Mail::Send;
       $msg->to($info{`email'});
       $msg->subject("Hey! Your lights are on! ");
       $fh = $msg->open();
       print $fh "$info{`name'},\n   Are you the owner of that ";
       print $fh "$info{`color'} $info{`make'} $info{`model'}?\n";
       print $fh "If so, your lights are on.\n";
       print $fh "Sincerely yours,\n$notifier\n";
       $msg->close();
       print "$info{`name'} has been notified! ";
    } else {
       print "<P>Sorry, that license plate number was not "
       print "found in our database<BR>\n";
    }
 }

You are now ready to write the main line code. In the case of the get request method, display the form; otherwise, process either the query or the notify action (see Listing 7.15).

Listing 7.15. The license plate notification CGI program.

#!/public/bin/perl5
 use CGI::Form;
 $q = new CGI::Form;
 print $q->header();
 print $q->start_html(-title=>`Lights Are On!');
 print "<H1>Lights Are On!</H1><HR>\n";
 if ($q->cgi->var(`REQUEST_METHOD') eq `GET') {
    &licensePlateForm($q);
 } else {
    my($action)=$q->param(`Action');
    if ($action eq `Query') {
       &printInfo($q->param(`LicensePlate'));
    } elsif ($action eq `Notify') {
       &notifyOwner($q->param(`LicensePlate'),$q->param(`FindersName'));
    }
 }
 print $q->end_html();

Review

This is another simple example that shows you how to send e-mail to someone from a CGI script. There are many other useful applications for this type of script, such as an automated request for information.

I hope you have obtained some valuable tips from this chapter on how to implement some basic tasks using Perl as your CGI implementation language. I will attempt to provide some more complex examples in later chapters, which will build on this foundation. I also hope that you find some of these algorithms useful and, more importantly, reusable, and I encourage you to share your own ideas with the rest of the Perl community.