I’m trying to use Perl to send an email message. Basically I have a Perl script that prints out a report in a nice format. I want that report to be sent via email. How can I
If the machine does not have sendmail configured, I typically use Mail::Sendmail
use Mail::Sendmail;
%mail = (smtp => 'my.isp.com:25',
to => 'foo@example.com',
from => 'bar@example.com',
subject => 'Automatic greetings',
message => 'Hello there');
sendmail(%mail) or die;
It's worth mentioning that if you happen to have Outlook on your machine and cpan the Outlook module:
# create the object
use Mail::Outlook;
my $outlook = new Mail::Outlook();
# start with a folder
my $outlook = new Mail::Outlook('Inbox');
# use the Win32::OLE::Const definitions
use Mail::Outlook;
use Win32::OLE::Const 'Microsoft Outlook';
my $outlook = new Mail::Outlook(olInbox);
# get/set the current folder
my $folder = $outlook->folder();
my $folder = $outlook->folder('Inbox');
# get the first/last/next/previous message
my $message = $folder->first();
$message = $folder->next();
$message = $folder->last();
$message = $folder->previous();
# read the attributes of the current message
my $text = $message->From();
$text = $message->To();
$text = $message->Cc();
$text = $message->Bcc();
$text = $message->Subject();
$text = $message->Body();
my @list = $message->Attach();
# use Outlook to display the current message
$message->display;
# Or use a hash
my %hash = (
To => 'suanna@live.com.invalid',
Subject => 'Blah Blah Blah',
Body => 'Yadda Yadda Yadda',
);
my $message = $outlook->create(%hash);
$message->display(%hash);
$message->send(%hash);
Note that the .invalid TLD is not real, so the address above will not deliver. In any case, I've put here a decent explanation of things in the module - this sends a message!
Simplest way without CPAN libraries:
#!/usr/bin/perl
$to = 'toAddress@xx.com'; # to address
$from = 'fromAddress@xx.com'; # from address
$subject = 'subject'; # email subject
$body = 'Email message content';# message
open(MAIL, "|/usr/sbin/sendmail -t");
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
print MAIL $body;
close(MAIL);
print "Email Sent Successfully to $to\n";
MIME::Lite is a strong module used by many. It's easy to use, including if you want to attach documents.
use MIME::Lite;
my $msg = MIME::Lite->new(
From => $from,
To => $to,
Subject => $subject,
Type => 'text/plain',
Data => $message,
);
$msg->send;
Since it uses sendmail
by default (as opposed to SMTP), you don't even need to configure it.