perl发送邮件

一个使用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中其他更加高级的模块。

更加详细的资料:

http://search.cpan.org/~gbarr/libnet-1.22/Net/SMTP.pm

http://zh.wikipedia.org/zh-cn/SMTP

posted @ 2012-08-01 20:50  akawhy  阅读(4442)  评论(1编辑  收藏  举报