Sending an email using Perl
Last Updated :
06 Mar, 2022
Perl allows its users to send mails using the Perl code-script. There are various ways to send email using Perl. These emails can be simple emails, emails with attachment, HTML formatted emails, emails with multiple receivers, etc.. Perl provides some modules for doing the same as well. In this article, we will go through some ways of sending an email using Perl-script.
Sendmail Utility
First, we will talk about Sendmail utility. You cannot expect excellent delivery rates by using it. Sometimes emails skipped the inbox. For Linux/Unix Sendmail is quick and simple to set up. For Windows and other devices, you’ll need to look at alternative approaches.
Sending Simple mail
perl
#!/usr/bin/perl
$subject = 'Sending mail using perl' ;
$message = 'Well that was easy!!' ;
open (MAIL, "|/usr/sbin/sendmail -t");
print MAIL "To: $to \n";
print MAIL "From: $from \n";
print MAIL "Subject: $subject \n\n";
print MAIL $message ;
$result = close (MAIL);
if ( $result )
{
print "Email Sent, Bro!\n";
}
else
{
print "There was a problem, Bro!\n";
}
|
Just add your and sender’s email id and the mail will be successfully sent and you will see quick results. If you don’t, make sure sendmail is configured properly on your machine and that the recipient’s email service doesn’t block emails coming from your IP address.

HTML Formatted email
What if the user wants to send html formatted text to the receiver? In that case just add below code as $message variable in your perl-script:
$message = '<h1>H1 is the main heading</h1><p><img src="image_source_with_extension" /></p>';
The above code will format your mail by following html syntax. You can use all the tags of html in the desired manner.
Adding CC and BCC fields
You can also add CC and BCC fields in message header. Add the following variables in your Perl-script:
$cc = '[email protected], [email protected], [email protected]';
$bcc = '[email protected]';
Adding an Attachment
It’s possible to add an attachment to a message, but it’s a bit more complex. Using this module and adding large files is probably a poor idea but you are good to go with small files.
Note: Before running the code below, make sure the Mail::Sendmail module is already installed.
perl
use MIME::QuotedPrint;
use MIME::Base64;
use Mail::Sendmail;
subject => 'Sending mail using perl' );
$boundary = "====" . time () . "====";
$mail { 'content-type' } = "multipart/mixed; boundary=\" $boundary \"";
$message = encode_qp( "Well that was easy!!" );
$file = $^X;
open (F, $file ) or die "Cannot read $file : $!";
binmode F; undef $/;
$mail {body} = encode_base64(<F>);
close F;
$boundary = '--' . $boundary ;
$mail {body} = <<END_OF_BODY;
$boundary
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
$message
$boundary
Content-Type: application/octet-stream; name="$^X"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="File_Name.pdf"
$mail{body}
$boundary--
END_OF_BODY
sendmail( %mail ) || print "Error: $Mail::Sendmail::error \n";
|
Note: Don’t forget to configure %mail section and filename section of $message variable.
MIME::Lite
This module offers more flexibility and is also available for non-Linux/Unix machines. By this module you can easily send the same mail to different receivers, format your mail using HTML tags, and also can send multiple attachments. MIME::Lite is intended as a simple, standalone module for generating MIME messages specifically, it allows you to output a simple, decent single- or multi-part message with a text or binary attachments. It does not require that you have the Mail:: or MIME:: modules installed but will work with them if they are. In order to install just write:
cpan -i MIME::Lite
or you can just download it from here.
Simple Mail
Below is the file which you will need to run in order to send the mail. The below code needs to be specified with “receiver’s mail address”, “sender’s mail address”, “subject” and “body” of the mail.
perl
#!/usr/bin/perl
use MIME::Lite;
$subject = 'Sending mail using perl' ;
$message = 'Well that was easy!!' ;
$msg = MIME::Lite->new(
From => $from ,
To => $to ,
Cc => $cc ,
Subject => $subject ,
Data => $message
);
$msg -> send ;
print "Email Sent Successfully!\n";
|
Now to verify that just check the receiver’s mail and you will see the image just like below:

HTML Formatted Mail
Just like the SendMail Utility, MIME::Lite Module also allows the users to send HTML formatted mails using the perl-script.
$message = '<h1>H1 is the main heading</h1><p><img src="image_source_with_extension" /></p>';
The above code will format your mail by following HTML syntax. You can use all the tags of HTML in the desired manner.
Sending same email to different receivers
Now the question is what if you have multiple receivers. In that case you have to do nothing just configure $to variable as:
$to = '[email protected], [email protected], [email protected]';
Note: Make sure to separate each mail address using comma(,)
Sending attachments
Attachment can be anything like document, pdf, or images. You can add a text message to your attachment. One of the advantages of this module is that it makes it easy to send attachments. You can include multiple files in a single email with attach() method. In order to send attachment just write:
perl
$msg ->attach( Type => 'text' ,
Filename => 'filename.extension' ,
Data => $message );
$msg ->attach( Type => 'image/gif' ,
Path => 'Provide_Full_Path' ,
Filename => 'Filename.extension' ,
Disposition => 'attachment' );
|
Last Step
So the final code after an above configuration like adding multiple receivers, formatting mail using HTML and adding attachment will look like:
perl
#!/usr/bin/perl
use MIME::Lite;
$subject = 'Sending mail using perl' ;
$message = 'Well that was easy!!' ;
$msg = MIME::Lite->new( From => $from ,
To => $to ,
Cc => $cc ,
Subject => $subject ,
Data => $message );
$msg ->attach( Type => 'text' ,
Filename => 'filename.extension' ,
Data => $message );
$msg ->attach( Type => 'image/gif' ,
Path => 'Provide_Full_Path' ,
Filename => 'Filename.extension' ,
Disposition => 'attachment' );
$msg -> send ;
print "Email Sent Successfully!\n";
|
MIME::Lite:TT::HTML
This is a variation of MIME::Lite which has increased its popularity. It is similar to MIME::Lite but different in the ability to use templates instead of hardcoding the content of messages.
In order to install this module:
cpan -i MIME::Lite::TT::HTML
Now first you will have to create a template for sending mail.
Filename: notice.txt.tt
This is from notice.txt
Filename: notice.html.tt
<p>This is from</p> <p>notice.html</p>
Now the configured source code using template will look like below.
perl
#!/usr/bin/perl
use strict;
use warnings;
use MIME::Lite::TT::HTML;
my %params ;
$params {first_name} = 'Piotr' ;
$params {client_name} = 'Jane' ;
my %options ;
$options {INCLUDE_PATH} = '/path/to/templates' ;
my $msg = MIME::Lite::TT::HTML->new(
Subject => 'Sending mail' ,
Template => { text => 'notice.txt.tt' ,
html => 'notice.html.tt' ,},
TmplOptions => \ %options ,
TmplParams => \ %params ,
);
$msg -> send ;
|
Sending Attachment
For sending attachments just add the below code after the $msg variable.
perl
$msg ->attr("content-type" => "multipart/mixed");
$msg ->attach( Type => 'application/pdf' ,
Path => '/path/to/prison_map.pdf' ,
Filename => 'prison_map.pdf' ,
Disposition => 'attachment' );
|
Note: Give complete path and full extension to add the file.
Now the complete source code will look like:
perl
#!/usr/bin/perl
use strict;
use warnings;
use MIME::Lite::TT::HTML;
my %params ;
$params {first_name} = 'Piotr' ;
$params {client_name} = 'Jane' ;
my %options ;
$options {INCLUDE_PATH} = '/path/to/templates' ;
my $msg = MIME::Lite::TT::HTML->new(
Subject => 'Sending mail' ,
Template => { text => 'notice.txt.tt' ,
html => 'notice.html.tt' ,},
TmplOptions => \ %options ,
TmplParams => \ %params ,
);
$msg ->attr("content-type" => "multipart/mixed");
$msg ->attach( Type => 'application/pdf' ,
Path => '/path/to/prison_map.pdf' ,
Filename => 'prison_map.pdf' ,
Disposition => 'attachment' );
$msg -> send ;
|
Using SMTP
By default, above methods use localhost for sending emails and locally setup server doesn’t guarantee that it will be delivered. Once you pick your provider or decide to set up an SMTP server on your own, adjust the code in your MIME modules and provide the SMTP credentials in send() method:
$msg->send('smtp', "smtp.example.com", AuthUser=>"your_id", AuthPass=>"your_password" );
Similar Reads
Scrapy - Sending an E-mail
Prerequisites: Scrapy Scrapy provides its own facility for sending e-mails which is extremely easy to use, and itâs implemented using Twisted non-blocking IO, to avoid interfering with the non-blocking IO of the crawler. This article discusses how mail can be sent using scrapy. For this MailSender c
2 min read
Sorting mixed Strings in Perl
Sorting in Perl can be done with the use of a pre-defined function 'sort'. This function uses a quicksort algorithm to sort the array passed to it. Syntax: sort @array Returns: a sorted array Sorting of an array that contains strings in the mixed form i.e. alphanumeric strings can be done in various
4 min read
Using curl to send email
In this article, we shall see how to harness the power of the "curl" command line tool and Gmail SMTP server in order to send an email programmatically using a bash script, "curl" is a versatile and powerful utility command line tool for making HTTP requests. And is primarily known for transferring
3 min read
Perl | Searching in a File using regex
Prerequisite: Perl | Regular Expressions Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to host language and are not the same as in PHP, Python, etc. Sometimes these are termed as "Perl 5 Compat
6 min read
How to Use Amazon SES For Email Sending?
Amazon SES (Simple Email Service) is a cloud-based email service that allows businesses to send both transactional and mass emails. Whether you want to send a welcome email, an invoice, or a promotional offer, Amazon SES provides a reliable and cost effective solution. In this guide, you will learn
6 min read
How to Send Email using NodeJS?
Sending emails programmatically is a common requirement in many applications, especially for user notifications, order confirmations, password resets, and newsletters. In this article, we will learn how to build a simple email-sending system using NodeJS. We will use Nodemailer, a popular module for
5 min read
Servlet - Sending Email
E-mail is considered the most secure, reliable, fast, and cheapest way of official communication over the internet. That's the reason every second almost 2.7M emails are being sent. Therefore, your Web-Application may need an email service for many needs like - communication, Multi-Factor Authentica
8 min read
Perl | Reading a CSV File
Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Reading a text file is a very common task in Perl. For example, you often come across reading CSV(Comma-Separated Value) f
7 min read
Email Writing - Format and Samples
Individuals and businesses alike have had to adapt their communication styles as a result of the rapid growth in internet use and associated economic activities. E-mails have largely replaced the function of post offices, which were formerly responsible for distributing our correspondence. Individua
8 min read
Perl - Extracting Date from a String using Regex
In Perl generally, we have to read CSV (Comma Separated Values) files to extract the required data. Sometimes there are dates in the file name like sample 2014-02-12T11:10:10.csv or there could be a column in a file that has a date in it. These dates can be of any pattern like YYYY-MM-DDThh:mm:ss or
5 min read