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.
#!/usr/bin/perl
use strict;
use warnings;
use Try::Tiny;
use IO::All;
use Email::MIME;
use Email::Sender::Simple qw(sendmail);
use Email::Sender::Transport::SMTP::TLS;
# Create and array of email parts.
# Here i have 2 attachments ( an image and a pdf file) and a text message.
my @parts = (
Email::MIME->create(
attributes => {
filename => "CUSTOM_FILENAME.jpg",
content_type => "image/jpeg",
encoding => "base64",
disposition => "attachment",
Name => "image.jpg"
},
body => io( "path_to/image.jpg" )->all,
),
Email::MIME->create(
attributes => {
filename => "CUSTOM_FILENAME.pdf",
content_type => "application/pdf",
encoding => "base64",
disposition => "attachment",
name => "document.pdf",
},
body => io( "path_to/document.pdf" )->all,
),
Email::MIME->create(
attributes => {
content_type => "text/html",
},
body => 'THIS IS A TEST EMAIL',
)
);
# Create the email message object.
my $email_object = Email::MIME->create(
header => [
From => 'USERNAME@gmail.com',
To => 'RECEIVER@gmail.com',
Subject => 'TEST MAIL!',
content_type =>'multipart/mixed'
],
parts => [ @parts ],
);
# Create the transport. Using gmail for this example
my $transport = Email::Sender::Transport::SMTP::TLS->new(
host => 'smtp.gmail.com',
port => 587,
username => 'USERNAME@gmail.com',
password => 'PASSWORD'
);
# send the mail
try {
sendmail( $email_object, {transport => $transport} );
} catch {
warn "Email sending failed: $_";
};
Hope it helps! 🙂