使用perl发送邮件

 

 最近有需要使用脚本发送邮件的需求,故整理了下资料,写了个send_mail的脚本。如下:

 

  • 脚本 mail.pl

 

 #!/usr/bin/perl

use Net::SMTP_auth;
#use strict;
use MIME::Base64;
use Encode;
use Encode qw(from_to);

####################################################
#发送邮件
#使用“cpan Net::SMTP_auth” 安装perl发送邮件需要的模块
#@param mailto 收件人
#@param subject 邮件主题
#@param msgFile (可选) 默认为/tmp/mailservice.out 调用之前先把待发送内容填充到 msgFile 
#脚本会自动获取文件里面的内容当内容发送。
#@author:  bimo
#@date:2013-08-09
####################################################

if(!@ARGV[0])   { 
        print "usage:","\n","mail.pl <mailto> <subject> [msg_contentfile]   \n";
        exit 0;
} 
if(!@ARGV[1])   { 
        print "usage:","\n","mail.pl <mailto> <subject> [msg_contentfile]   \n";
        exit 0;
} 
if(!@ARGV[2])   { 
        $msgFile="/tmp/mailservice.out";
}else{
        $msgFile=@ARGV[2];
}

        my $mail_content=`cat $msgFile`;
    my $to_address  = $ARGV[0];
    my $subject = $ARGV[1];;
    my $mail_user   = '[email protected]';
    my $mail_pwd    = '*****';
    my $mail_server = 'mail.xxx.com';

    my $from    = "$mail_user";

        print "run mail.pl to_address:",$to_address,"msg_contentfile:",$msgFile,"\n";

    my $smtp = Net::SMTP->new($mail_server);

    $smtp->auth($mail_user, $mail_pwd) || die "Auth Error! $!";
    $smtp->mail($mail_user);
    $smtp->to($to_address);

    $smtp->data();             # begin the data
    $smtp->datasend("To: $to_address\n");
        $smtp->datasend("Subject:=?utf-8?B?".encode_base64($subject,'')."?=\n\n");
        $smtp->datasend($mail_content);      # set content
    $smtp->dataend();   # end the data

    $smtp->quit();


#my $misc=`cat /dev/null > $msgFile` ;
#print "clean file:$msgFile, 's content result  $misc \n";

 

 

  • 执行测试 mail.pl

 

/usr/bin/perl mail.pl [email protected] 测试perl邮件发送 /tmp/mailservice.out

 
 

你可能感兴趣的:(perl)