Wednesday, July 20, 2011

Sending a text file in the body of an email using Perl

In Perl there is a package called Mail::Sendmail that could be used to send a simple text message.

The package for the module is libtimedate-perl (in hardy, Ubuntu 8.04.3 LTS)

dpkg -S Mail::Sendmail

#!/usr/bin/perl

use strict;
use warnings;

use Mail::Sendmail;

# Read the file into a string to put it into the mail hash variable
open FH, 'file.txt' or
        die "Error reading file.txt file: $!\n";
my @Lines = ;
chomp @Lines;
close FH;
my $Lines = join "\n", @Lines;

my $Recipients = 'somebody@mail.example';

my $Subject = 'Testing mail in Perl';

my %mail = (
        To => $Recipients,
        From => 'testing@mail.example',
        Subject => $Subject,
        Message => $Lines
);

$mail{Smtp} = 'mail.example';

if (sendmail %mail) {
        print "Mail sent OK.\n"
} else {
        print "Error sending mail: $Mail::Sendmail::error \n"
}

print "\n\$Mail::Sendmail::log says:\n", $Mail::Sendmail::log;

__END__

No comments: