如何用Net::SMTP发送邮件

简介: Code如下代码为用163.com的SMTP来发送邮件。 #!/usr/bin/perluse Net::SMTP;my $mailhost = "smtp.

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 = "此为正文/n第二行位于此。";

$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/n");
	$smtp->datasend("From: $mailfrom/n");
	$smtp->datasend("Subject: $subject/n");
	$smtp->datasend("/n");

	# Send the message
	$smtp->datasend("$text/n/n");

	# Send the termination string
	$smtp->dataend();
}
$smtp->quit;

TroubleShooting/Code Analysis

  • 为什么要 $stmp->auth('user','pass');
    大部分SMTP服务器为了防止 spam /垃圾邮件,就需要用户验证身份。
    此方法需要另外安装模块:Authen::SASL, 此模块可能系统不自带。
    如果系统为虚拟主机,而此模块无法安装,可使用Socket模块进行最直接的操作。详细的代码可以参考脚本LeoBBS或书籍《Perl网络编程》。
  • Debug => 1
    此段代码用于测试之用,所以开启了Debug,一般测试一次完毕,正式使用的话会关闭它。
  • 需要注意的是发信人和收信人的地址要用单引号,或者用"fayland/@gmail.com"。如果是个变量,需要用正则先将其转换。
    $mailto =~ s//@////@/;
  • 我想发送附件,该如何做?
    参考《Perl网络编程》。

邮件发送过程的简单介绍

SMTP协议由文档rfc821定义。
在rfc821协议中定义了两个角色,即发送者(用S表示,指发送邮件的程序)和接收者(用R表示,指SMTP服务器)。

  1. 在 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。
  2. 发送头文件。
    S: MAIL FROM: 
    R: 250 OK
    S: RCPT TO: 
    R: 
    这里的recipient的地址如果是在SMTP同一服务器上且服务器找不到此地址,就会回答"550 No such user here"。
  3. 发送正文。以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
  4. 退出连接。
    S: QUIT
    R: 221 server.com Service closing transmission channel


以上就是简易的连接过程。当开启Net::SMTP的debug的时候,就会输出类似于此连接过程的东西。

目录
相关文章
|
2月前
|
Ruby
|
3月前
|
数据安全/隐私保护 Ruby
|
3月前
|
数据安全/隐私保护 Ruby
|
5月前
|
网络安全 数据安全/隐私保护
用smtp发送邮件,语法错误,无法识别命令。 服务器响应为:Authentication is re
用smtp发送邮件,语法错误,无法识别命令。 服务器响应为:Authentication is re
92 0
|
8月前
|
网络安全 数据安全/隐私保护 Python
|
8月前
|
Python
|
8月前
|
Python
|
8月前
|
Python
|
网络安全 数据安全/隐私保护 Python
开心档-软件开发入门之Python SMTP发送邮件
本文主要讲解SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。