Published on Feb 10 2014 in Non-Java

How to send email from Perl using Net::SMTP, authentication and Unicode/UTF-8 encoding? Here goes minimalistic and tested code example.

#!/usr/bin/perl -w
use strict;
use Net::SMTP;
# needed for authentication
use Authen::SASL;
use utf8;
use Encode;
use MIME::Base64;

my $debug = 0;

# SMTP credentials
my $smtp_host = 'smtp.example.com';
my $smtp_user = '[email protected]';
my $smtp_pass = 'SeCrEt';

# mail properties
my $mail_from = '[email protected]';
my $mail_to = '[email protected]';
my $mail_subject = 'Example UTF-8 string: a';
my $mail_headers = "From: $mail_from\n".
"To: $mail_to\n".
"Subject: ".encode('MIME-Header',$mail_subject)."\n".
"MIME-Version: 1.0\n".
"Content-type: text/plain; charset=UTF-8\n".
"Content-Transfer-Encoding: base64\n\n";
my $mail_body = $mail_subject;

# send the email
my $smtp = Net::SMTP->new($smtp_host, Debug => $debug) or die "cannot connect to server";
$smtp->auth($smtp_user,$smtp_pass) or die "could not authenticate";
$smtp->mail($mail_from);
$smtp->to($mail_to);
$smtp->data();
$smtp->datasend($mail_headers);
$smtp->datasend(encode_base64(encode('utf8',$mail_body)));
$smtp->dataend();
$smtp->quit;

You can add additional headers, an attachment, SSL support, custom SMTP(S) port etc. Set $debug to 1 to see how the code talks with SMTP server.

Happy mailing!