Site icon Dipin Krishna

Perl: Send an Email with attachment through Gmail SMTP

perl

This is a tutorial on how to send an email with attachment via Gmail SMTP.
Here i am using Email::MIME to create the email/message object. Email::Sender::Simple (sendmail) is used to send the mail with the help of secure transport provided by Email::Sender::Transport::SMTP::TLS.

The sample script below sends an email with two attachments and a text/html message.

  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use Try::Tiny;
  5. use IO::All;
  6. use Email::MIME;
  7. use Email::Sender::Simple qw(sendmail);
  8. use Email::Sender::Transport::SMTP::TLS;
  9.  
  10. # Create and array of email parts. 
  11. # Here i have 2 attachments ( an image and a pdf file) and a text message.
  12. my @parts = (
  13.     Email::MIME->create(
  14.         attributes => {
  15.             filename      => "CUSTOM_FILENAME.jpg",
  16.             content_type  => "image/jpeg",
  17.             encoding      => "base64",
  18.             disposition   => "attachment",
  19.             Name          => "image.jpg"
  20.         },
  21.         body => io( "path_to/image.jpg" )->all,
  22.     ),
  23.     Email::MIME->create(
  24.         attributes => {
  25.             filename     => "CUSTOM_FILENAME.pdf",
  26.             content_type => "application/pdf",
  27.             encoding     => "base64",
  28.             disposition  => "attachment",
  29.             name         => "document.pdf",
  30.         },
  31.         body => io( "path_to/document.pdf" )->all,
  32.     ),
  33.     Email::MIME->create(
  34.         attributes => {
  35.             content_type  => "text/html",
  36.         },
  37.         body => 'THIS IS A TEST EMAIL',
  38.     )
  39. );
  40.  
  41. # Create the email message object.
  42. my $email_object = Email::MIME->create(
  43.     header => [
  44.         From           => 'USERNAME@gmail.com',
  45.         To             => 'RECEIVER@gmail.com',
  46.         Subject        => 'TEST MAIL!',
  47.         content_type   =>'multipart/mixed'
  48.     ],
  49.     parts  => [ @parts ],
  50. );
  51.  
  52. # Create the transport. Using gmail for this example
  53. my $transport = Email::Sender::Transport::SMTP::TLS->new(
  54.     host     => 'smtp.gmail.com',
  55.     port     => 587,
  56.     username => 'USERNAME@gmail.com',
  57.     password => 'PASSWORD'
  58. );
  59.  
  60. # send the mail
  61. try {
  62.        sendmail( $email_object, {transport => $transport} );
  63. } catch {
  64.        warn "Email sending failed: $_";
  65. };

Hope it helps! 🙂

Exit mobile version