Sending E-mail from Perl


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( '') or die "Cannot connect to host: $!";


$smtp->to( '' );

  $smtp->datasend("To: recipient\\n");
  $smtp->datasend("From: sender\\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!

Tags: perl