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

   

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

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

   

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

Comments on this post are now closed. If you want to get in touch with us to discuss this post please send us something on Twitter @revsys or use our contact form. Thanks!