May 15, 2012

send email in perl

There are 3 ways to send mail from Perl
  • shelling out to /usr/sbin/sendmail
  • using Net::SMTP directly when the application did not need to send attachments
  • using MIME::Lite when you did need to include attachments

Out of these MIME::Lite is best as it handles attachments and performance perspective.
Let us explain sending email using MIME::Lite 


#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use MIME::Lite;

    my $msg = MIME::Lite->new(
        From     =>'admin@example.com',
        To       =>'user@example.com',
        Subject  =>'testing a mail with attachments',
        Type =>'multipart/mixed'
    ) die "Error creating multipart container: $!\n";
  
    ### Add the text message part
    $msg->attach (
      Type => 'TEXT',
      Data => "Here is the attachment file(s) you wanted"
    ) or die "Error adding the text message part: $!\n";

    ### Add the GIF file
    $msg->attach (
       Type => 'image/gif',
       Path => my_file.gif,
       Filename => your_file.gif,
       Disposition => 'attachment'
    ) or die "Error adding $file_gif: $!\n";

    ### Add the ZIP file
    $msg->attach (
       Type => 'application/zip',
       Path => my_file.zip,
       Filename => your_file.zip,
       Disposition => 'attachment'
    ) or die "Error adding $file_zip: $!\n";

       $msg->send;

1;





No comments:

Post a Comment