Sending Email in Perl Using MIME-Lite

Album Cover: The Future

"The maestro says it's Mozart, but it sounds like bubble gum."
Leonard Cohen / Waiting For The Miracle

Posted on May 06, 2005 5:30 PM in Web Development
Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

If you're looking to send an email with attachments from your Perl script, it's super easy using MIME-Lite. There are some examples online, but from my perspective none of them are presented in a clear and precise way.

What better way to give an example than to just present an entire script, right? I've tested this works (with the email addresses and SMTP server correctly set, of course), so feel free to cut and paste for use in your own Perl script.

#!perl

# use MIME::Lite package
use MIME::Lite;

# set up email
$to = "mom\@example.com";
$from = "me\@example.com";
$subject = "Email Sent via Perl";
$message = "This email was sent using Perl.";
$file = "sample.txt";

# send email
email($to, $from, $subject, $message, $file);

# email function
sub email
{
 # get incoming parameters
 local ($to, $from, $subject, $message, $file) = @_;

 # create a new message
 $msg = MIME::Lite->new(
  From => $from,
  To => $to,
  Subject => $subject,
  Data => $message
 );

 # add the attachment
 $msg->attach(
  Type => "text/plain",
  Path => $file,
  Filename => $file,
  Disposition => "attachment"
 );

 # send the email
 MIME::Lite->send('smtp', 'mail.example.com', Timeout => 60);
 $msg->send();
}

This script can be modified pretty easily to send multiple attachments or attachments of different types (e.g. application/gzip or text/xml). Just remember to pay attention to your attachment Type value(s).

Comments

Trelis on July 09, 2005 at 2:27 AM:

Thanks a lot. Realy, I had no problems with this example.

Permalink

Srikanth on July 21, 2006 at 4:31 AM:

I tried exactly how it is said int he article. But at the receiver end, the mails go to "bulk" folder. Any idea?

Thanks
Srikanth

Permalink

sandeep on July 27, 2006 at 7:02 AM:

It gives me followng error when I try on Cygwin:
SMTP RCPT command failed:
Sorry, that domain isn't in my list of allowed rcpthosts.

Please help.

Permalink

Arul on December 12, 2006 at 6:59 AM:

Thanks! It helped.

Permalink

Paul on January 03, 2007 at 5:18 AM:

Hi, I can only get this script to work if I comment out

$msg->attach(
Type => "text/plain",
Path => $file,
Filename => $file,
Disposition => "attachment"
);

Have you any advice on why I am getting an Error 500 with the above code uncommented? Thanks.

Permalink

Bernie Zimmermann on January 03, 2007 at 7:36 AM:

Paul, if you're getting a 500 error I'm assuming you're trying to use the code as part of a web script. It's entirely possible that you don't have an attachment to send, so commenting out that portion of the code is the right thing to do. You could even modify the email() function so that it no longer accepts that fifth parameter.

If you are trying to send an attachment, though, make sure $file points to a valid location on your web server, otherwise the code will probably choke (resulting in the 500 error you're seeing) when attempting to attach the non-existent file. Good luck!

Permalink

Sean on May 08, 2007 at 1:08 PM:

Hi,
Good article... however, is there a way to send Mime Lite mail with multiple attachments of unknown type? So that an image, word doc, excel, etc can be included? I've looked for hours and can't find anything. Thanks.
Sean

Permalink

Frank Wiles on May 31, 2007 at 9:42 AM:

Great article. Just wanted to post a suggestion for others that they might want to look into using MIME::Lite::TT and MIME::Lite::TT::HTML modules. They are built upon MIME::Lite, but give you the ability to use Template Toolkit templates for the message body.

I wrote a small howto on the subject which is at:
http://www.revsys.com/writings/perl/sending-email-with-perl.html

Hope you find it useful.

Permalink

Matthew Lesko on January 10, 2008 at 7:06 AM:

I'm using a very simlar set of code as this:

$msg->attach(
Type => "text/plain",
Path => $file,
Filename => $file,


The program works. However when I get the email the file contents are printed inside the email versus being attached in my aol account. In a yahoo mail account it's attached and printed in the email and in gmail or MSoutlook it's printed in the email without an attachment. Any ideas how to force an attachment? I suspect it has to do with this part of the code:

if (-e $FilePath) {
# add parts
$msg->attach(Type =>'TEXT',
Data =>'# File Message'
);
$msg->attach(Type =>'text/html',
Path =>$FilePath,
Filename =>$file
);

Permalink

Jon Allen on January 17, 2008 at 3:38 PM:

Is there any way to send an attachment without writing it to a file first ?
I have a script that produces a list of CSV Data.
I want to send it as an attachment, without writing it to a temp file first. I can see that "attach" can take a file handle, but can't figure out if I can write to a File handle without writing to a temp file.

Permalink

Jon Allen on January 17, 2008 at 3:48 PM:

Cancel that. I just figured out you can use the Data option in attach.

Funny how as soon as get round to writing down the question in a detailed and unambiguous way , you end up solving it more easily.

Permalink

João Correia on January 30, 2008 at 11:24 AM:

I get this error....
"5.7.0 Must issue a STARTTLS command first g9sm11067582gvc.4"

What should I configure more?

Permalink

steve on May 15, 2008 at 4:57 PM:

i have this

...
63 # set up email
64 my $to = "bizsys.sa@ticketmaster.com";
65 my $from = "bizsys.sa@ticketmaster.com";
66 my $message = "This email was sent using Perl.";
67 my $log = "boa-push.log";
68
69 # send email
70 email($to, $from, $subject, $message, $log);
71
72 # email function
73 sub email
74 {
75 # get incoming parameters
76 local ($to, $from, $subject, $message, $log) = @_;
...



but get this error message ?

Can't localize lexical variable $to at steve.pl line 76.

Permalink

Bernie Zimmermann on May 15, 2008 at 8:16 PM:

Steve, what happens if you use my instead of local? Your script may be "strict"er than mine was at the time of writing.

Permalink

Thangadurai on August 27, 2008 at 2:55 AM:

i tried this code for sending email attachment.

for attach multiple files just add like this code

$dir="/usr/tmp/res-100/*.*";
$filecount=0;
foreach $file (glob $dir)
{

call email function
}

Permalink

vijayarl on September 23, 2008 at 5:22 AM:

Hi Bernie,

i have a querry, will this script holds good for sending the mail to multiple persons at one shot.
i mean can we add CC concepts to this script ???

Thanks,
Vijayarl

Permalink

vijayarl on September 23, 2008 at 6:39 AM:

Hi,

Am gettting this error when i try to run this script

C:Performance_svap>perl sendmail.pl
Net::CMD (Net::SMTP) DATASEND command failed.
Last server message was:Start mail input; end with .
This probably represents a problem with newline encoding at c:/perl/site/lib/MI
ME/Lite.pm line 2300

Can you help me out to reslove this issue ???

Permalink

Bernie Zimmermann on September 23, 2008 at 11:50 PM:

vijayarl, I'd recommend taking a look at line 2300 of Lite.pm (at the path suggested) and seeing if anything stands out. That's a pretty typical module, though, so you might also verify that you're running Perl in an expected or supported environment. Beyond that, though, it's hard to say what might be causing the problem. Good luck sorting it out.

Permalink

john bartels on October 20, 2008 at 7:23 PM:

I'm trying to use MIME:Lite to send messages in zoneminder with gmail. I set my SMTP mail server to smtp.gmail.com but don't I also need to provide parameters to log-in to gmail, like my gmail user id and password?

Permalink

Ram on October 24, 2008 at 9:32 PM:

Hi Bernie, I was able to get it working in the first go.

Any ideas on how to use SSL with Mime:Lite?

Thanks, Ram

Permalink

david russell on November 13, 2008 at 3:57 PM:

I inherited a system that uses MIME::LITE that also has Oracle installed. Oracle automatically puts a version of Perl on the host; however, the former DBA (four years ago) put a separate version (or more) on each host - and therefore did not use the easily available copy of 5.8.3 installed by default. I'm building new systems and trying not to install extra software.

How do I get MIME::LITE to be recongized... what is the path to whatever is needed, or do I have to install components that Oracle doesn't automatically install?

Thanks in advance for your help...

Permalink

Richard Jones on February 07, 2009 at 3:49 PM:

Hi - I am using a very similar method and it works to send the file that I am uploading from an HTML form. However, because I am using the file handle when I use Mime Lite then the file is embedded as well as attached. I do not seem to be able to find the "path" to the CGI copy of the file (fil handle) - do you ahve anu suggestions as how to send the file I upload using Mime lite without first saving it locally to the server and it still not be embedded at the end of the email.

Thanks

Permalink

Mayur on March 03, 2009 at 7:16 AM:

How to send an email from Lotus Notes using PERL script?

Can you please give me some idea?

I dont kow Lotus Notes.

Thanks in advance

Thanks,
Mac

Permalink

John on April 11, 2009 at 12:14 AM:

Hi,

I was able to send email including attachements using the code given above, but when I changed my network to a wireless broadband network, I started getting the below error:

"5.7.0 Must issue a STARTTLS command first. b7sm122712tic.15"

Do I need to configure something or add some othe line of code?

Any suggestions will be appreciated.

Thanks,
Gaurav

Permalink

hiren on June 05, 2009 at 6:26 AM:

Hi Bernie,

While attaching the file, system throws msg. like "d:hiren : access permission denied".

Can you plz give me some idea on this?

Thanks,
Hiren.

Permalink

Bernie Zimmermann on June 05, 2009 at 5:53 PM:

Hiren,

Is it possible you aren't double-escaping backslashes? Sometimes, when you don't do that, the file path you think you're sending ends up being something totally different.

Permalink

Seshu on June 18, 2009 at 8:35 AM:

I am using this script to send emails to a large group of users.I am trying to simlate a situation to check for email bounces. I put an invalid email id in 'cc'. The script is not throwing the below error and email is not sent to the other correct id's. Any help is greatly appriciated.
************************
SMTP RCPT command failed:
5.3.0 ... Unknown user - sorry.
************************

Permalink

kiss on August 24, 2009 at 12:07 AM:

What do you recommend for authentication? Net::SMTP?

Permalink

Rohaq on September 01, 2009 at 8:43 AM:

I'm also trying to figure out how to use Mime::Lite for SSL: Any takers?

Permalink

Shivaleela on November 05, 2009 at 4:55 AM:

i am not using the exact mail id but i do use initial which will get expanded but above fails if mail address initials has some spaces in bet ex "ASM Support All" we r using Lotus Notes

Permalink

Genadi Saltikov on July 13, 2010 at 6:12 AM:

I had my own share of fight with MIME::Lite class:

First of all, it may complain about missing SASL libraries (cpan would complain about pre-reqs missing too when installing them - you will have to solve that, or copy properly in perl/lib or site/lib etc.

Secondly, the attach block is misleading and wrong - Bernie I suggest you read the docs, perhaps it was changed since you posted this blog I dont know, but please look:

$msg->attach(
Type => "text/plain",
Path => $path.$file,
Disposition => "attachment"
);

You DONT need the Filename argument (its optional), in my case it only caused more trouble.
Now mails are sent out, with the original filename.
If you write Filename => $fullpath.$filename instead, your attachment will have the full path as part of its name :)

Hope that helps.

Permalink

Anush on September 17, 2010 at 5:24 AM:

Hi - I am using a very similar method and it works to send the file that I am uploading from an HTML form. However, because I am using the file handle when I use Mime Lite then the file is embedded as well as attached. I do not seem to be able to find the "path" to the CGI copy of the file (fil handle) - do you ahve anu suggestions as how to send the file I upload using Mime lite without first saving it locally to the server and it still not be embedded at the end of the email.

Thanks

Anush

Permalink

mathan on March 21, 2011 at 7:27 AM:

I tried to send the mail from one gmail user to another.ie i gave to and from address as a gmail ids..But its throwing error like "SMTP Failed to connect to mail server: Unknown error
at sendmail_MIME_LITE.pl line 41".

The error it throwing is on the line
MIME::Lite->send('smtp', 'gmail-smtp-in.l.google.com', Timeout => 60);
Here i used SMTP server address of gmail. I think i made some mistake here .Please help me in giving correct smtp server address here.Its urgent ...plz

Permalink

Bhargav on June 30, 2011 at 4:04 AM:

I have same kind of situation. Till now in my project there is a html which sends emails to users using perl script with single attachment. now the requirement is to allow multiple attachments . Hoe can i do this.
Can somebody help me.

Permalink

Yaerius on November 28, 2011 at 4:58 AM:

my comment is not a spam! why don't you let me post it?!

Permalink

arthirajan on July 16, 2012 at 11:53 PM:

i have an error "Can't modify non-lvalue subroutine call at my program"

Permalink

high PR blog commenting service on October 03, 2016 at 11:34 PM:

Nice knowledge gaining article. This post is really the best on this valuable topic.

Permalink

Piano For All Review on October 09, 2016 at 10:34 PM:

I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it..

Permalink

parker on November 26, 2016 at 1:51 PM:

Thanks for this article very helpful. thanks.

Permalink

Quadrocopter Versicherung on November 30, 2016 at 11:48 PM:

Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know.

Permalink

Atlam Mikey on February 05, 2017 at 9:56 PM:

Much obliged for offering pleasant data to us. i like your post and all you impart to us is uptodate and very instructive, i might want to bookmark the page so i can come here again to peruse you, as you have made a great showing.
trust flow blog comments

Permalink

James Cangelosie on February 19, 2017 at 10:16 PM:

You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! High Trust Flow Backlinks

Permalink

Post Comments

If you feel like commenting on the above item, use the form below. Your email address will be used for personal contact reasons only, and will not be shown on this website.

Name:

Email Address:

Website:

Comments:

Check this box if you hate spam.