Showing posts with label sendmail. Show all posts
Showing posts with label sendmail. Show all posts

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.

#!/usr/bin/perl

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

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 $!;
LOG->autoflush(1);
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;
        next;               
    }       
    if($cur_mday != $mday) {
        close(LOG);
        $logfile = $logdir."$smtpmailhost\_email_log\_$cur_datestamp.log";
        open LOG, ">>","$logfile" or die $!;
        LOG->autoflush(1);
        $mday = $cur_mday;
    }   
    $smtp->mail($from_address);
    $smtp->to($to_address);
    $smtp->data();
    $smtp->datasend("Subject: $smtpmailhost - Test email message\n");
    $smtp->datasend("\n");
    $smtp->datasend("Test email has been sent successfully at $cur_datestamp!");
    $smtp->dataend();
    $smtp->quit;
    print LOG "\n$cur_datestamp : Test Email sent via $smtpmailhost!";   
     sleep $interval;   
}

close(LOG);
sub usage
{
  print "Invalid parameters \nUsage: ./smtpemail_send.pl \n";
}




Please let me know, of any corrections/improvements.