---
title: "如何用Net::SMTP发送邮件"
author: "st780206"
date: "2010-04-01T16:44:44Z"
tags: []
categories: ["编程语言"]
slug: "net-smtp"
draft: false
lastmod: "2010-04-01T16:45:19Z"
id: 630192
url: "https://st780206.iteye.com/blog/630192"
---

[http://fayland.org/journal/NetSMTP.html](http://fayland.org/journal/NetSMTP.html)

 

Category: [Modules](/admin/blogs/Modules.html)   Keywords: **Net::SMTP mail**

## 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-&gt;auth('user','pass');  
  大部分SMTP服务器为了防止 spam /垃圾邮件，就需要用户验证身份。  
  此方法需要另外安装模块：Authen::SASL, 此模块可能系统不自带。  
  如果系统为虚拟主机，而此模块无法安装，可使用Socket模块进行最直接的操作。详细的代码可以参考脚本[LeoBBS](http://bbs.leobbs.com/)或书籍《Perl网络编程》。
- Debug =&gt; 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的时候，就会输出类似于此连接过程的东西。