Home > Perl > Modules and Packages > Sending Mail in Perl
Sending Mail in Perl
Written by Philip L Yuson   

Who is this for
This is for those who want to send mail from a Perl script.

What you need to know

You must know basic Perl scripting

Introduction

Why would you want to send mail from a Perl script? An example of this is when you received something from a webpage and you want to notify somebody of what was sent to your site. Or your script may have hit a condition that required some attention.

One way to do this is through the MIME::Lite package.

MIME::Lite package

The MIME::Lite package is used to generate MIME messages. The first thing you have to do is to install the MIME::Lite package. You can download this from CPAN or if you are using the Windows operating system, you can install this via the PPM or GPM – depending on your distribution.

Once installed, you can proceed to write a script to send a simple email message or even a mail with several attachments.

Sending a Simple Mail Message

Try this code. Change the email addresses to your own email address. This is written to use smtp servers to send your mail.

use MIME::Lite;			# Use the package
$msg = MIME::Lite->new( # create the MIME Object
From=>' This e-mail address is being protected from spambots, you need JavaScript enabled to view it ', # your email address
To=> ' This e-mail address is being protected from spambots, you need JavaScript enabled to view it ', # Receiver's email
Subject=>'This is a test MIME message', # subject
Type=>'TEXT', # Specify type
Data=> 'This is a sample Message'); # Message
MIME::Lite->send('smtp', # Send message
'your.smtpserver.com',
Timeout=>60);

The first line uses the MIME::Lite package. The second line creates the object. As you create the object, you define the parameters for the object. Replace the email addresses to your own email address and also replace the smtp server name.

To send the mail, you have to call the send subroutine from the MIME::Lite package and not from the $msg object.

Including an Attachment

To include an attachment, you can use the attach subroutine.

use MIME::Lite;		# use MIME::Lite
$msg = MIME::Lite->new( # Create object
From=>' This e-mail address is being protected from spambots, you need JavaScript enabled to view it ', # your email
To=> ' This e-mail address is being protected from spambots, you need JavaScript enabled to view it ', # receiver
Subject=>'This is a test MIME message', # Subject
Type=>'multipart/mixed'); # Type
$msg->attach(Type=>'TEXT',		# specify attachment
Data=> 'This is the message'); # attachment content
$msg->attach(Type=>'TEXT/HTML', # Specify attachment
Data=>'D:\datafile\perl\scripts'); # Data
MIME::Lite->send('smtp','your.smtpserver.com',Timeout=>60);	# Send

You can also change the Type parameter in the attach subroutine to attach a GIF file to 'image/gif'.

For more information on MIME::Lite, read the MIME::Lite documentation.



 
Copyright: © 2018 Philip Yuson