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.
