Sending an email using Perl

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
filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# Details for email
$to = 'user1@mail.abc';
$from = 'user2@mail.abc';
$subject = 'Sending mail using perl';
$message = 'Well that was easy!!';
  
open(MAIL, "|/usr/sbin/sendmail -t");
  
# Email Header
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
  
# Email Body
print MAIL $message;
  
$result = close(MAIL);
if($result
    print "Email Sent, Bro!\n";
else
    print "There was a problem, Bro!\n";
}

chevron_right


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 Formated 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 = 'user1@mail.abc, user2@mail.abc, user3@mail.abc';
$bcc = 'user4@mail.abc';
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.

filter_none

edit
close

play_arrow

link
brightness_4
code

use MIME::QuotedPrint;
use MIME::Base64;
use Mail::Sendmail;
%mail = ( from => 'user1@mail.abc',
          to => 'user2@mail.abc'
          subject => 'Sending mail using perl');
  
$boundary = "====" . time() . "====";
$mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\"";
  
$message = encode_qp( "Well that was easy!!" );
  
# This is the perl executable
$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";

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
use MIME::Lite;
   
$to = 'receiver_mail@anything.com';
$cc = 'anyone@anything.com';
$from = 'sender_mail@anything.com';
$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";

chevron_right


Now to verify that just check the receiver’s mail and you will see the image just like below:



HTML Formated 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 = 'receiver1_mail@anything.com, receiver2_mail@anything.com, receiver3_mail@anything.com';

Note: Make sure to seperate 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Add text message.
$msg->attach(Type => 'text'
             Filename => 'filename.extension'
             Data => $message);
              
# Specify your file as attachment.
$msg->attach(Type => 'image/gif',
             Path => 'Provide_Full_Path',
             Filename => 'Filename.extension',
             Disposition => 'attachment');     

chevron_right


Last Step

So the final code after an above configuration like adding multiple receivers, formatting mail using HTML and adding attachment will look like:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
use MIME::Lite;
  
$to = 'receiver1_mail@anything.com, receiver2_mail@anything.com, receiver3_mail@anything.com';
$cc = 'anyone@anything.com';
$from = 'sender_mail@anything.com';
$subject = 'Sending mail using perl';
$message = 'Well that was easy!!';
  
$msg = MIME::Lite->new(From     => $from,
                       To     => $to,
                       Cc     => $cc,
                       Subject => $subject,
                       Data     => $message);
  
# Add text message.
$msg->attach(Type     => 'text'
             Filename => 'filename.extension'
             Data     => $message);
              
# Specify your file as attachment.
$msg->attach(Type     => 'image/gif',
             Path     => 'Provide_Full_Path',
             Filename => 'Filename.extension',
             Disposition => 'attachment'); 
                  
$msg->send;
print "Email Sent Successfully!\n";

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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(
    From => 'user1@mail.abc',
    To => 'user2@mail.abc',
    Subject => 'Sending mail',
    Template => {text => 'notice.txt.tt',
                 html => 'notice.html.tt',},
    TmplOptions => \%options,
    TmplParams => \%params,
);
  
$msg->send;

chevron_right


Sending Attachment

For sending attachments just add the below code after the $msg variable.

filter_none

edit
close

play_arrow

link
brightness_4
code

$msg->attr("content-type" => "multipart/mixed");
  
$msg->attach(Type => 'application/pdf',
             Path => '/path/to/prison_map.pdf',
             Filename => 'prison_map.pdf',
             Disposition => 'attachment');

chevron_right


Note: Give complete path and full extension to add the file.

Now the complete source code will look like:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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(
    From => 'user1@mail.abc',
    To => 'user2@mail.abc',
    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;

chevron_right


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" );



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.