Code
如下代码为用163.com的SMTP来发送邮件。
#!/usr/bin/perl
use Net::SMTP;
my $mailhost = "smtp.163.com"; # the smtp host
my $mailfrom = "notfour@163.com"; # your email address
my @mailto = ("fayland@gmail.com", "not_four@hotmail.com"); # the recipient list
my $subject = "此为标题";
my $text = "此为正文
第二行位于此。";
$smtp = Net::SMTP->new($mailhost, Hello => "localhost", Timeout => 120, Debug => 1);
# anth login, type your user name and password here
$smtp->auth("user","pass");
foreach my $mailto (@mailto) {
# Send the From and Recipient for the mail servers that require it
$smtp->mail($mailfrom);
$smtp->to($mailto);
# Start the mail
$smtp->data();
# Send the header
$smtp->datasend("To: $mailto
");
$smtp->datasend("From: $mailfrom
");
$smtp->datasend("Subject: $subject
");
$smtp->datasend("
");
# Send the message
$smtp->datasend("$text
");
# Send the termination string
$smtp->dataend();
}
$smtp->quit;
TroubleShooting/Code Analysis
邮件发送过程的简单介绍
SMTP协议由文档rfc821定义。
在rfc821协议中定义了两个角色,即发送者(用S表示,指发送邮件的程序)和接收者(用R表示,指SMTP服务器)。
- 在 S 和 R 通过套接连接后,S应当先向R表明身份,此过程用helo命令完成,helo后连接发送者的域名(可用localhost)。而R的回答是一个表示连接成功的状态码和服务器身份等。例如:
S: helo 1313s.com
R: 220 server.com Simple Mail Transfer Service Ready 数据挖掘交友
在rfc821定义的状态码中,通常以2或3开头的表示成功,以4或5开头的表示传输过程出现了问题。
如果是需要服务器身份验证的话,还用发送AUTH LOGIN。 - 发送头文件。
S: MAIL FROM:
R: 250 OK
S: RCPT TO:
R:
这里的recipient的地址如果是在SMTP同一服务器上且服务器找不到此地址,就会回答"550 No such user here"。 - 发送正文。以DATA开始。以两个换行结束。
S: DATA
R: 354 Start mail input; end with (两个换行)
S: To: recipient@whereau.com
S: From: someone@somewhere.com
S: subject: title
S: ...
S: text
S: etc.
S:
S:
R: 250 OK 数据挖掘工具
- 退出连接。
S: QUIT
R: 221 server.com Service closing transmission channel 数据挖掘交友
以上就是简易的连接过程。当开启Net::SMTP的debug的时候,就会输出类似于此连接过程的东西。