new($smt...">

Perl: Method to send a simple SMTP message

This is a quick method to send an SMTP email message using on core Perl modules.

use Net::SMTP;
use Time::Piece;

my $smtp_server = "mail.server.com";
my $smtp        = Net::SMTP->new($smtp_server, Timeout => 3, Hello => 'hostname.server.com');

my $err;
my $ok = send_email('to@domain.com', 'from@domain2.com', 'Test subject', '<b>HTML</b> body', \$err);

if (!$ok) { print "Error: $err" }
sub send_email {
    my ($to, $from, $subject, $html_body, $err) = @_;

    $smtp->mail($from);
    my $ok = $smtp->to($to);

    if ($ok) {
        # Ghetto strip tags
        my $text_body = $html_body =~ s/<[^>]*>//rgs;
        my $sep       = time() . "-$smtp_server";

        my $headers  = "To: $to\n";
        $headers    .= "From: $from\n";
        $headers    .= "Subject: $subject\n";
        $headers    .= "Date: " . localtime->strftime() . "\n";
        $headers    .= "Message-ID: <" . time() . "\@$smtp_server>\n";
        $headers    .= "Content-type: multipart/alternative; boundary=\"$sep\"\n\n";
        $headers    .= "This is a multi-part message in MIME format\n\n";

        # Text version
        $headers .= "--$sep\n";
        $headers .= "Content-Type: text/plain\n\n";
        $headers .= "$text_body\n\n";

        # HTML version
        $headers .= "--$sep\n";
        $headers .= "Content-Type: text/html\n\n";
        $headers .= "$html_body\n\n";

        # Closing separator
        $headers .= "--$sep--\n";

        $smtp->data();
        $smtp->datasend($headers);
        $smtp->dataend();
    } else {
        $$err = $smtp->message();
    }

    return $ok;
}
Leave A Reply
All content licensed under the Creative Commons License