Google搜查列

 

2008年10月2日 星期四

Perl使用 mail::sendmail MIME::Base64

最近要需要把server上的一些資訊
每天定時的E-mail到指定信箱

是管理員看倒是還好
但是是長官有要看,就要用HTML的mail格式了

HTML還要插入圖片,這下就不是那麼簡單了

努力了幾天,可以找到幾個套件,合併使用,可以達到我要的目的

用來把文字編碼成Base64的套件 MIME::Base64;
郵件寄送套件 Mail::Sendmail;

注意同顏色的變數,要一樣的才會插入圖片生效
而且最好用outlook收件才會有效果

#!/usr/bin/perl

use MIME::QuotedPrint;
use HTML::Entities;
use Mail::Sendmail 0.75; # doesn't work with v. 0.74!
use Mysql;
use MIME::Base64;

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "useracc";
$tablename = "acc";
$user = "bird";
$pw = "12345";

# PERL MYSQL 建立連線()
$connect = Mysql->connect($host, $database, $user, $pw);

# SELECT DB 選擇資料庫
$connect->selectdb($database);

$myquery = "SELECT * FROM $tablename";

# EXECUTE THE QUERY 對連線下指令
$execute = $connect->query($myquery);

#取回得到的資料放入變數 $retnumber
my $retnumber = $execute->numrows();

#SQL CLOSE
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#使用localtime()取得現在時間
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =localtime(time);

#年份要加上1900才是公元
$year=$year+1900;
#月份要加上1才正確
$mon=$mon+1;

#開始要預先編輯html的內容放入變數
my $html="$year 年 $mon 月 $mday 日 $hour : $min
";
$html=$html."$tablename 現在有$retnumber 筆資料
";

#使用. 符號合併 字串

#$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ FILE encode64
#放入附件前,要先把圖檔作編碼為base64
open(FILE, "/home/eth0-day.png") or die "$!";
while (read(FILE, $buf, 60*57)) {
$ee= encode_base64($buf);
$ff =$ff.$ee;
}
close FILE;
#$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ FILE encode64

#=================== mail資訊
%mail = (
from => 'report@domain.com',
to => 'you@domain.com',
subject => "XXX Server $year/$mon/$mday $hour:$min Report",
);
#=================== mail資訊end

#一些標準標籤設定宣告一下
$boundary = "====" . time() . "====";
$boundary = '--'.$boundary;
$mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\"";

$file = $^X; # This is the perl executable

open (F, $file) or die "Cannot read $file: $!";
binmode F; undef $/;
$mail{body} = encode_base64();
close F;

#---------------------------------- 真正編輯mail標頭及內容
$mail{body} = << END_OF_BODY;
$boundary Content-Type: text/html;
charset="UTF-8" Content-Transfer-Encoding: quoted-printable

$html
< src=""cid:eth0-day.png>

$boundary
Content-Type: image/png;
name="eth0-day.png"
Content-Transfer-Encoding: base64
Content-ID: <656020898@300920332-0c65>
Content-Description:
Content-Location: eth0-day.png"

$ff

$boundary--
END_OF_BODY

#---------------------------------- 真正編輯mail標頭及內容 結束


#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 使用MAIL::SENDMAIL 寄出郵件
sendmail(%mail) || print "Error: $Mail::Sendmail::error\n";

1 則留言:

alexchen 提到...

剛好我也有類似的需求,您的做好給了我很好的參考,感謝您.

Google Analytics