Perl: Send Email


A Perl sample code to send a file’s content by either Gmail or local SMTP.

#!/user/bin/perl -w

use strict;
use Net::SMTP; # used by local SMTP
use Net::SMTP::TLS; # used by Gmail

# Read the file content from error_log
open( my $error, “<error_log”);
my @log = <$error>;

# If error_log is empty, then do nothing
if (scalar(@log) == 0) {
    close $error;
}

# Send out the error_log contents
else {
    # Define the mail settings here
    # Option1: Use local SMTP server   
    #my $mailhost = ‘192.168.1.200’;
    #my $sender = ‘sender@mydomain.com’;
    #my $recipient = ‘recipient@mydomain.com’;
    #my $smtp = Net::SMTP->new(“$mailhost”);
   
    # Option2: Use Gmail
    my $sender = ‘xxxxx@gmail.com’;
    my $pwd = ‘******’;   
    my $recipient = ‘xxxxx@anydomain.com’;
    my $smtp = new Net::SMTP::TLS(
    ‘smtp.gmail.com’,
    Port    =>    587,
    User    =>    “$sender”,
    Password=>    “$pwd”,
    Timeout =>    30
    );   
   
    #Mail header and body   
    my $subject = ‘Error message’;
    $smtp->mail(“$sender”);
    $smtp->to($recipient);
    $smtp->data();
    $smtp->datasend(“To: $recipient \n”);
    $smtp->datasend(“From: $sender \n”);
    $smtp->datasend(“Subject: $subject \n” );
    $smtp->datasend(“\n”);
    $smtp->datasend(“@log”);
    $smtp->datasend(“\n”);
    $smtp->dataend();
    $smtp->quit;

    close $error;

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s