Friday, October 24, 2014

A simple Perl script to send an email with attachment

Following is a simple email sending script in Perl, it also shows how to send an attachment file along with the email.

#!/usr/bin/perl

use MIME::Lite; # required module for formatting and sending the email using sendmail  

my $msg = MIME::Lite->new(
 From    => 'youraddress@youraddress.com', # sender email address
 To      => 'toaddress@toaddress.com',  # recipient email address 
 Cc      => 'ccaddress@ccaddress.com',  # optional, mention Cc recipient email address if required
 Type    => 'text/plain',   # main body type of the email, here it is text
 Subject => 'Email sending script exapmple', # mail subject line
 Data    => 'My first email sending perl script with an image file attachment', # main email body text
);

# the following portion is optional, required only in case of sending file attachments with the email 
$msg->attach(
 Type     =>'image/gif',   # attachment file type, here it is an image file
 Path     =>'/var/www/html/test.jpg', # location of the file in the server i.e to be attached with the email
 Filename =>'my_attachment.jpg'  # optional, only required for renaming the file attached in the email 
);

if ($msg->send()) # email sent and the returned status checked
{
 print "Mail sent successfully";
}
else
{
 print "Unable to send mail";
}


Output:
-------
It will send an email along with the attachment to the mentioned recipients on execution of the script.