How to send an email in Perl

In this shot, we’ll learn how to write a program in Perl to send an email from one id to another.

There are several ways to send an email from different Operating Systems using Perl.

Linux/Unix OS

If you are working on a Linux/Unix PC, there is a sendmail utility in a Perl app through which you can easily send an email to the recipient.

Windows and other OS

Unlike Linux/Unix, there is no utility such as sendmail in Windows through which we can send an email. As an alternative, the Perl module MIME:Lite can be used for client-side email writing. This module can be locally installed on the machine.

send mail process in perl

Code

Example 01 - Plaintext

Below is a basic syntax for sending an email through Perl:

$to = 'receiver@educative.io';
$from = 'sender@educative.io';
$subject = 'Sending Plaintext with Perl';
$message = 'Test program to send email through Perl!';
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 sending success!\n"; }
else {
print "Email sending failed!\n"; }

Explanation

To ensure that the email is sent successfully, the email server needs to be configured correctly on the host machine’s operating system.

Example 02 - HTML message

Below is another example of sending an email through the Perl program:

$to = 'receiver@educative.io';
$from = 'sender@educative.io';
$subject = 'Sending HTML message with Perl';
$message = '<h1>Hello Sir!</h1>
<p>How are you doing?</p>
<p>Hope you received my gifts and letters!</p>
<p>Do respond to this email.</p>
<p>Thank you!</p>';
open(MAIL, "|/usr/sbin/sendmail -t");
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n";
print MAIL "Content-type: text/html\n\n";
print MAIL $message;
close(MAIL);
print "Email sent successfully!\n";

Explanation

If we observe closely, the only significant difference between sending a Plaintext and HTML message is the Content-type: text/html\n.

This Content-type specifies that this is an HTML message mail, and the message includes an HTML syntax.

Since HTML has various tags such as: <p>, <h1> to <h6>, <img>, etc. We can include these tags in our HTML message and send attachments with them like images, links/urls, documents.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved