Net::SMTP Simple Example

Net::SMTP is a fairly simple module to use. At a minimum, you need the following bits of information:

The text of the message determines how the message appears in the reader's mail client. There are several different options you can use, and I will address them separately.

Basic SMTP Example

The script below shows the bare minimum commands required to send an email via Net::SMTP:

    #!/usr/bin/perl -w

    use Net::SMTP

    $SMTP_HOST  = 'your.smtphost.com';

    sub send_mail
    {
        my ($from, $to_addr, $msg);

        $from       = shift;
        $to_addr    = shift;
        $msg    = shift;

        #
        # Open a SMTP session
        #
        $smtp = Net::SMTP->new( $SMTP_HOST,
                                'Debug' => 0,       # Change to a 1 to turn on debug messages
                            );

        if(!defined($smtp) || !($smtp))
        {
            print "SMTP ERROR: Unable to open smtp session.\n";

            return 0;
        }

        #
        # Pass the 'from' email address, exit if error
        #
        if (! ($smtp->mail( $from ) ) )
        {
            return 0;
        }

        #
        # Pass the recipient address(es)
        #
        if (! ($smtp->recipient( ( ref($to_addr) ? @$to_addr : $to_addr ) ) ) )
        {
            return 0;
        }

        #
        # Send the message
        #
        $smtp->data( $msg );

        $smtp->quit;
    }

    sub main
    {
        send_mail(
                'from@domain.com',
                'to@domain.com',
                'This is a brief email.\n'
        );
    }

In the example above, there would not have been a subject line. In addition, there might not be a Sent Date, From, or To value in the recipient's email client. Formatting the email message is as important as the commands to send the email. Through formatting the message, the recipient's mail client will display the message better.

Formatting an Email with Header Information

Basic formatting of the message will vastly improve the display on the recipient's email client. Several fields are good to include in the message to facilitate this. Those fields are:

The basic fields must be in the message in the order above to ensure that the client will react to them properly. A properly formatted message would look like this example:

    MIME-Version: 1.0
    From: "Joe Somebody" 
    To: "Jane Somebody" 
    Date: Monday, 1 January 1980 14:30:02 -500
    Subject: Monday

    Just wanted to send you an email to say hi.  Hi!

    Joe

I wrote a date function, equivalient to "date -r" on Unix systems, to properly format the date for use in an email header. The function is not necessarily the most efficient, but it does the job.

    sub date_r
    {
        my ($day, $mon, $str);
        my (@lt) = ();

        @lt     = localtime();
        $day    = $lt[6];
        $mon    = $lt[4];

        $str = $DAYS[$day] . ", " . $lt[3] . " " . $MON[$mon] . " " . ($lt[5]+1900)
             . " " . sprintf("%02d:%02d:%02d", $lt[2], $lt[1], $lt[0] )
            . " " . sprintf("%03d%02d", (tz_offset() / 3600), 0);

        return $str;
    }

Now we are ready to format our message body through code. We will update the prior example of the subroutine "send_mail". Note that a double \n is required after the last line of the header to notify the mail client to display the next section in the message body field.

    sub send_mail
    {
        my ($from, $to_addr, $body, $msg);

        $from       = shift;
        $to_addr    = shift;
        $body       = shift;


        $msg = "MIME-Version: 1.0\n"
             . "From: $from\n"
             . "To: " . ( ref($to_addr) ? join(';', @$to_addr) : $to_addr ) . "\n"
             . "Date: " . date_r() . "\n"
             . "Subject: $subject\n\n"      # Double \n
             . $body;

        #
        # Open a SMTP session
        #
        $smtp = Net::SMTP->new( $SMTP_HOST,
                                'Debug' => 0,       # Change to a 1 to turn on debug messages
                            );

        if(!defined($smtp) || !($smtp))
        {
            print "SMTP ERROR: Unable to open smtp session.\n";

            return 0;
        }

        #
        # Pass the 'from' email address, exit if error
        #
        if (! ($smtp->mail( $from ) ) )
        {
            return 0;
        }

        #
        # Pass the recipient address(es)
        #
        if (! ($smtp->recipient( ( ref($to_addr) ? @$to_addr : $to_addr ) ) ) )
        {
            return 0;
        }

        #
        # Send the message
        #
        $smtp->data( $msg );

        $smtp->quit;
    }

You are all set to send email via the Net::SMTP module now. For examples on how to send HTML formatted email, or attachments, see the other examples on this website.

Return to Home