Generally, I would use
MIME::Tools to build the message, then send it via /usr/bin/sendmail. The critical part is the formatting, and then the actual hand off is to an external Mail Agent. Here is some example code which assumes Linux-like environment. This script could be called sendemail and the command line arguments can be deduced from the line with the @ARGV. The attachments are files, and are optional. A more complete script would include documentation, of course. Note that this sends email to whatever SMTP host your system is configured to send mail to; it does not send just
through gmail, but can send anywhere, including to addresses @gmail.com
#!/usr/bin/perl
# SSF 071710 send email example for Perlmonks
use strict;
use warnings;
use vars qw/$cmdMail/;
use LWP::MediaTypes qw(guess_media_type read_media_types);
use MIME::Entity;
BEGIN {
$cmdMail='/usr/lib/sendmail'; # location of your sendmail
read_media_types('/etc/mime.types'); # location of your mime.types
+ file
}
sub sendmail { # returns undef or error
my ($from,$to,$subject,$body,@attachments)=@_;
my $ret;
my $top=build MIME::Entity
From => $from,
'Reply-to' => $from,
To => $to,
Subject => $subject,
Data => $body;
if (@attachments) {
for my $path (@attachments) {
my $type=guess_media_type($path);
$top->attach(
Path => $path,
Type => $type,
Encoding => '-SUGGEST'
);
}
}
$top->sync_headers(Length=>'COMPUTE') if @attachments;
if (open(MAIL,"| $cmdMail -t -i")) {
$top->print(\*MAIL);
close MAIL;
} else {
$ret="Mail to $to failed: $!";
}
$ret;
}
my ($from,$to,$subject,$body,@attachments)=@ARGV;
my $err=sendmail($from,$to,$subject,$body,@attachments);
die $err if $err;
exit;
The code creates the properly formatted message, and knows how to add each attachment with its proper formatting and media type (which it figures out with a little help from
LWP::MediaTypes, and then it has to sync the headers to compute the length of the message. MIME::Entity does the internal work of generating a proper separating line for the different parts of a multi-part message, and does it only when you call the attach method.
HTH,
SSF
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.