Perl FAQ: How do I send e-mail from a Perl/CGI program on a Unix system?

Question: How do I send e-mail from a Perl/CGI program on a Unix system?

Answer:

Sending e-mail from a Perl CGI program on a Unix computer system is usually pretty simple. Most Perl programs directly invoke the Unix sendmail program. We'll go through a quick example here.

Assuming that you've already have e-mail information you need, such as the send-to address and subject, you can use this sample Perl code to generate and send the e-mail message:

#  the rest of your program is up here ...

   open(MAIL, "|/usr/lib/sendmail -t");

   print MAIL "To: $sendToAddress\n";
   print MAIL "From: $myEmailAddress\n";
   print MAIL "Subject: $subject\n";

   print MAIL "This is the message body.\n";
   print MAIL "Put your message here in the body.\n";

   close (MAIL);

#  more of your program ...

As you can see from this sample code, sending e-mail from Perl programs on Unix systems is pretty simple. Once you know the "To:", "From:", "Subject:", and message body information, the sending part is very simple!

As a final note, be careful to check the location of the sendmail program on your Unix system. It may be located in different directories on different Unix systems.

Happy coding!

What's Related


devdaily logo