How do I attach multiple files to an email using Perl?
-
27-10-2019 - |
Question
I find it hard to believe that this question doesn't exist on SO, but I couldn't find an instance or one similar for Perl....
Anyway, what Perl module should I use to attach multiple files to an email?
Currently, I'm using this code to send an email with a single attachment, but I couldn't figure out how to modify it to handle multiple attachments:
my $mail_fh = \*MAIL;
open $mail_fh, "|uuencode $attachment $attachment |mailx -m -s \"$subject\" -r $sender $recipient";
print $mail_fh $message;
close($mail_fh);
Can this code block be modified to handle multiple attachments? Or do I have to use a special module to pull this off? If so, what is the module and how would I script it out?
Thanks for any help!
Solution
I ended up going with an example using MIME::Lite
found here
use MIME::Lite;
use Getopt::Std;
my $SMTP_SERVER = 'smtp.server.com'; #change
my $DEFAULT_SENDER = 'default@sender.com'; #change
my $DEFAULT_RECIPIENT = 'default@recipient.com'; #change
MIME::Lite->send('smtp', $SMTP_SERVER, Timeout=>60);
my (%o, $msg);
# process options
getopts('hf:t:s:', \%o);
$o{f} ||= $DEFAULT_SENDER;
$o{t} ||= $DEFAULT_RECIPIENT;
$o{s} ||= 'Files';
if ($o{h} or !@ARGV) {
die "usage:\n\t$0 [-h] [-f from] [-t to] [-s subject] files ...\n";
}
# construct and send email
$msg = new MIME::Lite(
From => $o{f},
To => $o{t},
Subject => $o{s},
Data => "Data",
Type => "multipart/mixed",
);
while (@ARGV) {
$msg->attach('Type' => 'application/octet-stream',
'Encoding' => 'base64',
'Path' => shift @ARGV);
}
$msg->send( );
example usage:
./notify_mime.pl -f cheese -t queso -s subject /home/id/cheeseconqueso/some_dir/example1.xls /home/id/cheeseconqueso/some_other_dir/*.xls
OTHER TIPS
See attach_file
in Email::Stuff, or Email::MIME if you need more control.
Despite mixed ratings, I've found Mail::Sender (and it's pal Mail::Sender::Easy) darn good and straightforward to use, and looks like it can handle multiple attachments.
I found the interface to be extremely annoying in Mail::Internet.
Anything should be better than what you have above, though. :-)