Thursday, November 12, 2009

Command line email with attachments

This is a perl script which can be used as a replacement for "mail" program, but supporting email attachments.


#!/usr/bin/perl -w

#****h* common/send_files
# NAME
# send_files - sends an email with multiple file attachments
# FUNCTION
# Uses sendmail to send an email with attachments. Takes message text
# from the standard input.
# PARAMETERS
# --from - From email address
# --to - To email address
# --subject - Email subject
# --file - Attach a file (use multiple times to attach multiple files)
#
# All the unprocessed options are treated as files to be attached
#
# EXAMPLE
# echo "Look here" | send_files --from from@example.com --to to@example.com \
# --subject "Files" --file /tmp/1.txt --file /tmp/2.txt
#
# echo "Specify files last" | send_files --from from@example.com --to to@example.com \
# --subject "Files" --file /tmp/*.txt
# HISTORY
# $Header: send_files.pl,v 1.6 2008/04/08 20:53:13 nsushkin Exp $
# SOURCE
#
use MIME::Lite;
use MIME::Types;
use Getopt::Long;

my ($opt_from, $opt_to, $opt_subject) = ("", "", "");
my @files = ();
my $VERSION = sprintf("%d.%03d", q$Revision: 1.6 $ =~ /(\d+)\.(\d+)/);

GetOptions("from=s" => \$opt_from,
"to=s" => \$opt_to,
"subject=s" => \$opt_subject,
"file=s" => \@files);

push @files, @ARGV;
$oldC = $/;
binmode STDIN; undef $/;
$message=<STDIN>;
$/ = $oldC;

$msg = MIME::Lite->new(
From => $opt_from,
To => $opt_to,
Subject => $opt_subject,
Type => 'TEXT',
Data => $message
);

$msg->replace(
'X-Mailer' => "send_files.pl $VERSION"
);

for $file (@files)
{
die "Not readable $file: $!" unless -r $file;
chomp (my $mimeTypeS=`file -bi "$file"`);
my MIME::Type $mimeType = MIME::Types->new->type($mimeTypeS);
chomp (my $fileName=`basename "$file"`);

$msg->attach(
Type => $mimeTypeS,
Path => $file,
Filename => $fileName,
Encoding => ($mimeType->mediaType eq 'text' ? 'quoted-printable' : 'base64')
);
}

$msg->send;
#***

No comments: