Tidbits | Jan. 5, 2006

Sending E-mail from Perl

by Frank Wiles |   More posts by Frank

UPDATE: I've recently found an even better way of sending Email messages than using any of the information listed here. Check out my new post on the subject for the details

I'm always amazed at how many people have trouble doing something as simple as sending E-mail from Perl or mod_perl. I think this is because new Perl programmers are either unaware of CPAN or afraid to use it. Trust me CPAN is your friend. :) If you install the Net::SMTP module, which is part of the libnet CPAN package, on your system it is trivial to send plain text E-mail messages.

Here is a brief example:

Create an instance of the module

my $smtp = Net::SMTP->new( 'smtp.example.com') or die "Cannot connect to host: $!";

$smtp->to( 'recipient@example.com' );

$smtp->datasend("To: recipient\@example.com\n");
$smtp->datasend("From: sender\@example.com\n");
$smtp->datasend("Subject: Test Subject\n");
$smtp->datasend("This is where the body of your message goes!\n");

This module assumes you know a little bit about the SMTP protocol, but there are tons of modules on CPAN that are even easier to use. This one just happens to be the one I use the most. Some others are:

While I haven't personally used all of these modules, they all seem to have clean interfaces for sending E-mail from your Perl programs. MIME::Lite especially is useful when you want to send attachments along with your message. Hopefully this information helps you in your future projects!


2006-01-05T11:22:53 2018-04-18T16:00:01.157133 2006 perl