How do I set up outbound SMTP using MIME::Lite and Net::SMTP_auth in Perl?
|
|||||||||||||
Problem:How do I set up outbound SMTP using Perl? Solution:The following example of code shows you how to send an email using outMail as the SMTP SmartHost mail relay using the MIME::Lite and Net::SMTP_auth modules for perl. outMail is an authenticated SMTP relay so the example below shows authentication in perl as well. The code below uses the default SMTP port 25 but it can easily be changed to an alternative SMTP port by changing the port parameter in the Net::SMTP_auth library. In this example we generate a multipart MIME message with a HTML message and an alternative text message. Example code smtp-mime-test.pl #!/usr/bin/perl -w
use MIME::Lite;
use Net::SMTP_auth;
use strict;
use warnings;
my $smtphost = 'mxXXXXXX.smtp-engine.com';
my $smtpport = 25;
my $smtpuser = 'outmail-username';
my $smtppass = 'outmail-password';
my $msgFrom = 'me@example.com';
my $msgTo = 'recipient@example.com';
my $msgSubject = 'Test message';
# #################################################################
# Lets build the MulitPart MIME Message
# #################################################################
# Create the Message
my $msg = MIME::Lite::->new(
'To' => $msgTo,
'From' => $msgFrom,
'Subject' => $msgSubject,
'Type' => 'multipart/alternative',
);
# Create the text part
my $text_part = MIME::Lite::->new(
'Type' => 'text/plain',
'Data' => 'Hi\nThis is a test message',
);
# Create the HTML part
my $html_part = MIME::Lite::->new(
'Type' => 'multipart/related',
);
$html_part->attach(
'Type' => 'text/html',
'Data' => '
Hi This is a test message ',
);
# Now lets attach the text and html parts to the message
$msg->attach($text_part);
$msg->attach($html_part);
my $email = $msg->as_string();
# #################################################################
# Lets sent the Message
# #################################################################
my $smtp = Net::SMTP_auth->new($smtphost, Port=>$smtpport) or die "Can't connect";
$smtp->auth('PLAIN', $smtpuser, $smtppass) or die "Can't authenticate:".$smtp->message();
$smtp->mail($msgFrom) or die "Error:".$smtp->message();
$smtp->recipient($msgTo) or die "Error:".$smtp->message();
$smtp->data() or die "Error:".$smtp->message();
$smtp->datasend($email) or die "Error:".$smtp->message();
$smtp->dataend() or die "Error:".$smtp->message();
$smtp->quit or die "Error:".$smtp->message();
exit 0;
Summary of server details
| |||||||||||||
|