Sunday, July 25, 2010

Perl - send email without using sendmail

In a recent exercise, I was required to write a script which would attempt sending email through an smtp server instead of sendmail. At a periodic interval, the script would check if the smtp server is able to send emails or not. Basically, this script ran as a background process.


use Net::SMTP;
use POSIX qw/strftime/;
if (@ARGV != 5)

my $smtpmailhost = $ARGV[0];
my $from_address = $ARGV[1];
my $to_address = $ARGV[2];
my $timeout = $ARGV[3];
my $interval = $ARGV[4];

my $logdir = "/tmp/email_logs/";

my $datestamp = strftime('%m-%d-%y_%H:%M:%S',localtime);
$mday = (localtime(time))[3];

my $logfile = $logdir."$smtpmailhost\_email_log\_$datestamp.log";
open LOG, ">>","$logfile" or die $!;
while(1) {
    $smtp = Net::SMTP->new($smtpmailhost,
                            Timeout => $timeout);
    $cur_datestamp = strftime('%m-%d-%y_%H:%M:%S',localtime);
    $cur_mday = (localtime(time))[3];
    if(!$smtp) {
        print LOG "\n$cur_datestamp : Error creating smtp object for $smtpmailhost: $!";
        sleep $interval;
    if($cur_mday != $mday) {
        $logfile = $logdir."$smtpmailhost\_email_log\_$cur_datestamp.log";
        open LOG, ">>","$logfile" or die $!;
        $mday = $cur_mday;
    $smtp->datasend("Subject: $smtpmailhost - Test email message\n");
    $smtp->datasend("Test email has been sent successfully at $cur_datestamp!");
    print LOG "\n$cur_datestamp : Test Email sent via $smtpmailhost!";   
     sleep $interval;   

sub usage
  print "Invalid parameters \nUsage: ./ \n";

Please let me know, of any corrections/improvements.


Anonymous said...

I would like to exchange links with your site
Is this possible?

Harpreet said...

Let me know what links you want to exchange.

Anonymous said...

Sorry for my bad english. Thank you so much for your good post. Your post helped me in my college assignment, If you can provide me more details please email me.