CGI

ID #84

How do I use sendmail with perl?

Applies to: Grid System

You can either specify who the mail will be sent to as you print to the MAIL filehandle like so:

#!/usr/bin/perl

unless(open (MAIL, "|/usr/sbin/sendmail -t")) {
print "error.\n";
warn "Error starting sendmail: $!";
}
else{
print MAIL "From: me\@mydom.com\n";
print MAIL "To: test\@testdom.com\n";
print MAIL "Subject: test subject\n\n";
print MAIL "test mail message";
close(MAIL) || warn "Error closing mail: $!";
print "Mail sent.\n";
}

or you can specify who the mail will be sent to as you invoke sendmail:

#!/usr/bin/perl

unless(open (MAIL, "|/usr/sbin/sendmail recipient\@someplace.com")) {
print "error.\n";
warn "Error starting sendmail: $!";
}
else{
print MAIL "From: me\@mydom.com\n";
print MAIL "Subject: test subject\n\n";
print MAIL "test mail message";
close(MAIL) || warn "Error closing mail: $!";
print "Mail sent\n";
}

Last update: 2010-09-29 16:40
Author: FAQ Admin
Revision: 1.2

Digg it! Share on Facebook Print this record Send FAQ to a friend Show this as PDF file
Please rate this FAQ:

Average rating: 4 (3 Votes)

completely useless 1 2 3 4 5 most valuable

You can comment this FAQ

Comment of Anonymous:
In addition to the sample code modwest shows there are *many* perl modules that make assembling and sending mail a snap.

MIME::Lite is great for attachments (sending images or attached files) and Mail::Mailer is a terrific pick for simple plain text or HTML mail. Here's a sample:


#!/usr/bin/perl
use warnings;
use strict;
#----------------------------------------------
use Mail::Mailer qw(sendmail);
#----------------------------------------------
my $mail = Mail::Mailer->new('sendmail')
or die "Couldn't create a mail object!\n";

my $myself = $ENV{USER} . '@' . $ENV{HOST};

my $mail_headers = {
'Content-Type' => 'text/plain',
To => [ 'tuna@fish.net', $myself ],
From => $ENV{USER} . '@sedition.com',
Subject => "Testing, 1, 2, 5 -- 3, Sire!",
};

$mail->open( $mail_headers );

$mail->print("This message has no body!\n",
"Except this of course...");

$mail->close();

exit 0;
#----------------------------------------------

Added at: 2002-09-30 00:10