有時候我們在部署指令碼的時候,我們想知道,我們的程式執行的怎麼樣了,想得到執行的結果,這樣我們也能放心很多是吧,那麼在程式執行成功或失敗的時候能夠給我沒發個郵件很是很不錯的。
其實利用perl發郵件的方法有很多種,包括你在cpan上搜尋mail關鍵字是一大堆,經過實踐,MIME::Lite用來發郵件還是很合適的,最不可思議的是它可以幫你輕鬆的發送帶有附件的郵件哦。
下面我們就以MIME::Lite發郵件為例:
在cpan上面有關於它的詳細的用法(http://search.cpan.org/~rjbs/MIME-Lite-3.028/lib/MIME/Lite.pm)
它發郵件的方式有兩種,第一種最簡單就是利用系統自身的mail程式,比如sendmail來進行,運行sendmail當然也許要具有root的許可權了
另一個就是通過smtp的方式了,我們會以網易的163郵箱為例說明。
我們先以預設發送方式(sendmail)為例說明:
複製代碼 代碼如下:
#!/usr/bin/perl -w
use MIME::Lite;
my $msg = MIME::Lite->new(
From => ‘chenqing663@163.com',
To => ‘chenqing663@foxmail.com',
Cc => ‘some@other.com, some@more.com',
Subject => ‘hello,my first mail from chenqing.org',
Type => ‘multipart/mixed',
Data =>' other data'
);
$msg->attach(
Type => ‘image/png',
Disposition => ‘attachment',
Filename => ‘other.png',
Path => ‘/home/king/perl/logo.png'
);
$msg->send;
再來一個html格式的:
複製代碼 代碼如下:
#!/usr/bin/perl -w
use MIME::Lite;
my $msg = MIME::Lite->new(
From => ‘chenqing663@163.com',
To => ‘chenqing663@foxmail.com',
Cc => ‘some@other.com, some@more.com',
Subject => ‘hello,my first mail from chenqing.org',
Type => ‘multipart/mixed',
Data =>' other data'
);
$msg->attach(
Type => ‘text/html',
Data => qq{
<body>
這是我的 <b>good</b> image:
<img src=”cid:logo.png”>
</body>
},
);
$msg->attach(
Type => ‘image/png',
Disposition => ‘attachment',
Filename => ‘other.png',
Id => ‘logo.png',
Path => ‘/home/king/perl/logo.png'
);
$msg->send;
下面看看怎麼用smtp的方式發送:
複製代碼 代碼如下:
#!/usr/bin/perl -w
use MIME::Lite;
use MIME::Base64;
use Authen::SASL;
my $host='smtp.163.com';
my $pass='yourpass';
my $user='xxx@163.com';
my $msg = MIME::Lite->new(
From => ‘xxx@163.com',
To => ‘chenqing663@foxmail.com',
Cc => ‘some@other.com, some@more.com',
Subject => ‘hello,my first mail from chenqing.org',
Type => ‘multipart/mixed',
Data =>' other data'
);
$msg->attach(
Type => ‘text/html',
Data => qq{
<body>
這是我的 <b>good</b> image:
<img src=”cid:logo.png”>
</body>
},
);
$msg->attach(
Type => ‘image/png',
Disposition => ‘attachment',
Filename => ‘other.png',
Id => ‘logo.png',
Path => ‘/home/king/perl/logo.png'
);
MIME::Lite->send(‘smtp', $host, Timeout=>60, AuthUser=>$user, AuthPass=>$pass);
$msg->send;
是不是很簡單呢?