Send Email with Attachment Programmatically

In this article, we describe how to send email with attachment programmatically. This can be useful when you want to send your files including binary files to your email box for backup and you don't want to send them one by one manually which can be tedious and error-prone.

Sending email in batches is also useful when you want to upload your files to photo management and sharing sites such as Picasa and Flickr that support the email upload feature. We know that there exist tools that allow you to upload your photos easily. The drawback is that unless that tool supports multiple photo sites otherwise you have to use different tools to upload the same photos to different web sites.

Following we describe how to send email with attachment in Perl. You first need to install the MIME::Lite package from CPAN which allows you to create MIME email easily. Depending on your local environment, you may need to install a few other dependent packages such as Email::Date and etc.

The Perl script we write accepts an argument that is a directory name and then the script searches all the JPEG files in that directory. This can be done easily with the glob function in Perl.

  my ($dir) = (@ARGV);
  my @files = glob("$dir/*.JPG");

Next we just need to retrieve the filenames one by one and use MIME::Lite to construct the email messages. The MIME::Lite package has a constructor with which you can fill in the From, To, CC addresses and a few other fields.

  my $msg = MIME::Lite->new(
    From => 'yuonlamp@yahoo.com',
    To =>'yuonlamp@yahoo.com',
    Cc =>'yuonlamp@yahoo.com',
    Subject => $subject,
    Type =>'TEXT',
    Data => $subject,
  );

Next you can call the attach function to attach the file. Because usually there is a limit on the size of email attachment, you'd better send one attachment per email.

  $msg->attach(
    Type =>'image/jpeg',
    Path => $filename,
    Filename => $filename,
  );

Please note that the Path argument specifies the location of the file on your local disk and the Filename argument specifies the name that the receiver will see.

At last you can call the MIME::Lite's send function to send the email out.

  $msg->send();

Putting the message construction and sending code in a loop that retrieves the filenames one by one and we can send all the photo files in a batch.

You can download the complete sample Perl script to send email with attachment in a batch and adapt it to your local environment.

Back to articles on development