天天看點

使用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([email protected][0])   { 
        print "usage:","\n","mail.pl <mailto> <subject> [msg_contentfile]   \n";
        exit 0;
} 
if([email protected][1])   { 
        print "usage:","\n","mail.pl <mailto> <subject> [msg_contentfile]   \n";
        exit 0;
} 
if([email protected][2])   { 
        $msgFile="/tmp/mailservice.out";
}else{
        [email protected][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