« Using SSH ControlMaster to speed up your connect times | Main | Perl DB2 Article »

January 05, 2006

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!

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/t/trackback/2117594/7220996

Listed below are links to weblogs that reference Sending E-mail from Perl:

Comments

Post a comment

Comments are moderated, and will not appear on this weblog until the author has approved them.

If you have a TypeKey or TypePad account, please Sign In