1. Computing

Creating a Simple Email Function

By

Sometimes you're forced to work with a less than ideal installation of Perl. Many hosts don't have and don't allow Perl modules to be installed, or run outdated versions. One of the handiest things you can have in your quick function library is a simple email routine that doesn't require anything special to be available - other than sendmail.

Here is the full code we'll be working with:

 #	Simple Email Function
 #	($to, $from, $subject, $message)
 sub sendEmail
 {
 	my ($to, $from, $subject, $message) = @_;
 	my $sendmail = '/usr/lib/sendmail';
 	open(MAIL, "|$sendmail -oi -t");
 		print MAIL "From: $from\n";
 		print MAIL "To: $to\n";
 		print MAIL "Subject: $subject\n\n";
 		print MAIL "$message\n";
 	close(MAIL);
 } 

Using the function is straightforward. Simply pass it the data in the correct order.

 sendEmail( TO Email, FROM email, SUBJECT of email, BODY of email ); 

Like so:

 sendEmail("toemail\@mydomain.com", "fromemail\@mydomain.com", "Simple email.", "This is a test of the email function."); 

Let's take a look at the function bit by bit. The first line pulls in the variables passed in when the function is called.

 my ($to, $from, $subject, $message) = @_; 

Then we set the path to sendmail in an easily edited variable. This is really more for convenience than anything else. If you need to find sendmail on your server, try typing 'whereis sendmail' at the prompt.

 my $sendmail = '/usr/lib/sendmail'; 

Now comes the meat of the function. We're going to open a filehandle (or reference) to sendmail and then print the email directly to it. First we create the MAIL reference and aim it at sendmail.

 open(MAIL, "|$sendmail -oi -t"); 

The next bit simply prints the email to the filehandle:

 print MAIL "From: $from\n";
 print MAIL "To: $to\n";
 print MAIL "Subject: $subject\n\n";
 print MAIL "$message\n"; 

Then close the handle and we're done.

 close(MAIL); 

And that's it. If you have a newer setup, or you have control over what Perl modules are installed, you might explore more robust options like Mail::Sendmail. Part of being an effective programmer or administrator is being able to quickly adapt or solve problems, though, and this is a simple, and quite effective solution, especially on older systems.

Related Video
Creating Webpage Frames
  1. About.com
  2. Computing
  3. Perl
  4. CGI & Web
  5. Email
  6. Creating a Simple Email Function

©2014 About.com. All rights reserved.