一個使用perl發送郵件的小程序,主要用到了Net::SMTP模塊。對於發送簡單的郵件可以很輕松的搞定。注意,使用前需要安裝libauthen-sasl-perl,可以利用apt-get安裝或者到cpan上下載安裝,否則調用auth函數總會失敗。
直接進入正題,這里以163郵箱做一個小例子(mail_user需要開啟smtp服務):
use Net::SMTP; # mail_user should be your_mail@163.com sub send_mail{ my $to_address = shift; my $mail_user = 'your_mail@163.com'; my $mail_pwd = 'your_password'; my $mail_server = 'smtp.163.com'; my $from = "From: $mail_user\n"; my $subject = "Subject: here comes the subject\n"; my $message = <<CONTENT; ********************** here comes the content ********************** CONTENT 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($from); # set user $smtp->datasend($subject); # set subject $smtp->datasend($message); # set content $smtp->dataend(); $smtp->quit(); }
這里$from與$subject不是必須的。不過如果不設置的話,對方看到的郵件將看不見主題和發件人。SMTP模塊是不支持設置主題和發件人,因此只能利用手動發送From和Subject來設置了。具體請參考SMTP協議~
如果想在郵件里添加附件之類的東西可以參考cpan中其他更加高級的模塊。
更加詳細的資料: