Programming      contents


How to send email from Perl script?      contents

Below is example:

#!/usr/bin/perl -Tw
use Mail::Mailer;
# http://www.zeegee.com/code/perl/MIME-tools/download/
use MIME::Words qw(:all);
use strict;

my $charset='UTF-8';
# default /usr/bin/mail mailer strips mime headers, use 'sendmail' or 'smtp'
my $mailer = Mail::Mailer->new('sendmail');
# my $mailer = new Mail::Mailer 'smtp', Server => $server;
my $body = qq{
ąčęėįšųūž
фифи
日本語
};
$mailer->open({
	From    => encode_mimewords('Ričardas <rch@localhost>', Charset => $charset),
	To      => encode_mimewords('Ričardas <rch@localhost>', Charset => $charset),
	Subject => encode_mimewords('perl test ąčęėįšųūž', Charset => $charset),
	'MIME-Version' => '1.0',
	'Content-Type' => "text/plain; charset=$charset",
	'Content-Transfer-Encoding' => '8bit',
       })
or die "Can't open: $!\n";
print $mailer $body;
$mailer->close();

encode_mimewords() is required in general case because many server side email programs mangle raw 8 bit bytes in email headers. If you don't have MIME::Words Perl module installed please ask your server admin to do that. Or you can do that yourself if you are your own admin:

/root 2$ su
Password:
~ #su3# perl -MCPAN  -e shell

cpan shell -- CPAN exploration and modules installation (v1.48)
ReadLine support enabled

cpan> install MIME::Words
	...
cpan> quit
Lockfile removed.
~ #su3# 

Another usefull Perl module is Text::Iconv, allowing to use libc iconv() for conversion between different encodings. You can use it with GNU libiconv or with glibc v2.1.95 or newer.




How to send email from shell script?      contents

Unix /bin/sh scripts often use old "mail" command for email sending. Unfortunately it doesn't support MIME, but you can use mutt command instead:

cat /tmp/message_body.txt
|mutt -s 'Message Subject' -n -F/dev/null
-e 'set charset=UTF-8 from="Sender <foo@bar.com>"' rch@localhost
Note: It is wrapped here but all this should be on single line.

Add additional -a ./my_attachment_file.zip key to mutt if you want to attach some file.



  Valid XHTML 1.0!