Perl - Emailing MULTIPLE files as attachment

Hi Guys,

I would love an example as to how I can send multiple files in one email using perl. The file types are .csv

I have read that mimencode is required? Is there any other way or is that it?

Thanks :slight_smile:

There is a very eloquent example in cookbook.

#!/usr/bin/perl -w
# mail-attachment - send files as attachments
 
use MIME::Lite;
use Getopt::Std;
 
my $SMTP_SERVER = 'smtp.example.com';           # CHANGE ME
my $DEFAULT_SENDER = 'sender@example.com';      # CHANGE ME
my $DEFAULT_RECIPIENT = 'recipient@example.com';# CHANGE ME  
 
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} ||= 'Your binary file, sir';
 
if ($o{h} or !@ARGV) {
    die "usage:\n\t$0 [-h] [-f from] [-t to] [-s subject] file ...\n";
}
 
# construct and send email
 
$msg = new MIME::Lite(
    From => $o{f},
    To   => $o{t},
    Subject => $o{s},
    Data => "Hi",
    Type => "multipart/mixed",
);
 
while (@ARGV) {
  $msg->attach('Type' => 'application/octet-stream',
               'Encoding' => 'base64',
               'Path' => shift @ARGV);
}
 
$msg->send(  )

Include attached files when you run script.

Otherwise, you can do it the hard way.

#!/usr/bin/perl -w
 
use MIME::Lite; 

$msg = MIME::Lite->new( 
	From => 'you@yoursite.com', 
	To => 'you@yoursite.com', 
	Subject => 'Multiple attachments', 
	Type => 'multipart/mixed');
 
$msg->attach(	Type		=>'text/plain', 
		Path 		=>"/data/file1.csv", 
		Filename 	=>"file1.csv");

$msg->attach(	Type		=>'text/plain', 
		Path 		=>"/data/file2.csv", 
		Filename 	=>"file2.csv");

$msg->attach(	Type		=>'TEXT',
		Data		=>'Hello mom');
 

## Attach etc...

$msg->send();	#sendmail(1) or $msg->send('smtp', 'mailserver.yoursite.com');

I do not think there is another way then MIME.

That example should be fine!

Thanks Mate :slight_smile:

or also in perl just use the back ticks and execute shell code from your perl command.

but yeah if you want to stay completely perl then one of the above is better.