Archive

Archive for the ‘emailing’ Category

Sending message with attachements using Mail::Sender in Perl

September 8, 2011 Leave a comment

Due to the security setting of a network, not every server is allowed to send out email directly, that’s the reason why I wrote this script. The following Perl packages are required: Mail::Sender and Getopt::Long. Feature that would be nice to have but hasn’t been supported yet: smtp authentication. Therefore in order to be able to run this script, the external smtp server should add the ip of server where mail.pl runs to the allow-to-send list, assuming the smtp server is not configured to be a open relay.

cat mail.pl

#!/usr/bin/perl
# purpose of this script is to address the followings:
# 1) support simple sending through external smtp server that doesn't require authentication
# 2) attach file(s) while sending message
# run the script without parameters will print the usage
# example usage:
# echo "message sent using mail.pl" | perl mail.pl -f sender@email.address -s "sending test" -a file1.txt -a info.log john@email.address,smith@email.address
use strict;
use warnings;
use Mail::Sender;
use Getopt::Long;

my $subject='[NO SUBJECT]';
my @attach=();
my $from='unspecified_sender@company.ltd'; # change this
my $through='localhost';
my $help=0;

usage() if ( @ARGV < 1 or
    ! GetOptions(
        'attach|a=s@'=>\@attach,
        'subjec|st=s'=>\$subject,
        'from|f=s'=>\$from,
        'through|t=s'=>\$through,
        'help|h'=>\$help,
    ) or $help );
 
sub usage
{
  print "Unknown option: @_\n" if ( @_ );
  print "usage: program [--subject|-s SUBJECT] [--from|-f FROM] [--through|-t SMTP] [--attach|-a FILE]  [--help|-h] recipient1@domain1[,recipient2@domain2...]\n";
  print "Suject will become [NO SUBJECT] if not provided.\n";
  print "Multiple --attach can be supplied to attach more than 1 file\n";
  exit;
}

my $to=$ARGV[0];

# check if files exist
map {
    die("File $_ doesn't exist!\n") if ! -f $_;
} @attach;

my $msg='';
while(<STDIN>) {
    $msg.=$_;
}
if($msg eq '') {
    $msg='[BLANK]';
}

my $sender=new Mail::Sender( {
    smtp=>$through,
    from=>$from,
});

$sender->OpenMultipart( {
    to=>$to,
    subject=>$subject,
});

$sender->Body();
$sender->SendLine($msg);
$sender->SendFile( {
    description=>'Raw data File',
    encoding=>'7BIT',
    file=>\@attach
});
$sender->Close();
Categories: emailing, perl