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 = ‘’;
    #my $sender = ‘’;
    #my $recipient = ‘’;
    #my $smtp = Net::SMTP->new(“$mailhost”);
    # Option2: Use Gmail
    my $sender = ‘’;
    my $pwd = ‘******’;   
    my $recipient = ‘’;
    my $smtp = new Net::SMTP::TLS(
    Port    =>    587,
    User    =>    “$sender”,
    Password=>    “$pwd”,
    Timeout =>    30
    #Mail header and body   
    my $subject = ‘Error message’;
    $smtp->datasend(“To: $recipient \n”);
    $smtp->datasend(“From: $sender \n”);
    $smtp->datasend(“Subject: $subject \n” );

    close $error;



Leave a Reply

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

You are commenting using your 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 )

Connecting to %s