> For the complete documentation index, see [llms.txt](https://go.xiao5.info/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://go.xiao5.info/di-san-bu-fen-go-gao-ji-bian-cheng/15.0/15.12.md).

# 用 smtp 发送邮件

`smtp` 包实现了用于发送邮件的“简单邮件传输协议”（Simple Mail Transfer Protocol）。它有一个 `Client` 类型，代表一个连接到 SMTP 服务器的客户端：

* `Dial()` 方法返回一个已连接到 SMTP 服务器的客户端 `Client`
* 设置 `Mail`（from，即发件人）和 `Rcpt`（to，即收件人）
* `Data()` 方法返回一个用于写入数据的 `Writer`，这里利用 `buf.WriteTo(wc)` 写入

示例 15.26 [smtp.go](https://github.com/MartialBE/the-way-to-go_ZH_CN/blob/master/eBook/examples/chapter_15/smtp.go)

```go
package main

import (
	"bytes"
	"log"
	"net/smtp"
)

func main() {
	// Connect to the remote SMTP server.
	client, err := smtp.Dial("mail.example.com:25")
	if err != nil {
		log.Fatal(err)
	}
	// Set the sender and recipient.
	client.Mail("sender@example.org")
	client.Rcpt("recipient@example.net")
	// Send the email body.
	wc, err := client.Data()
	if err != nil {
		log.Fatal(err)
	}
	defer wc.Close()
	buf := bytes.NewBufferString("This is the email body.")
	if _, err = buf.WriteTo(wc); err != nil {
		log.Fatal(err)
	}
}
```

如果需要认证，或有多个收件人时，也可以用 `SendMail()` 函数发送。它连接到地址为 `addr` 的服务器；如果可以，切换到 TLS（“传输层安全”加密和认证协议），并用 PLAIN 机制认证；然后以 `from` 作为发件人，`to` 作为收件人列表，`msg` 作为邮件内容，发出一封邮件：

```go
func SendMail(addr string, a Auth, from string, to []string, msg []byte) error
```

示例 15.27 [smtp\_auth.go](https://github.com/MartialBE/the-way-to-go_ZH_CN/blob/master/eBook/examples/chapter_15/smtp_auth.go)

```go
package main

import (
	"log"
	"net/smtp"
)

func main() {
	// Set up authentication information.
	auth := smtp.PlainAuth(
		"",
		"user@example.com",
		"password",
		"mail.example.com",
	)
	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	err := smtp.SendMail(
		"mail.example.com:25",
		auth,
		"sender@example.org",
		[]string{"recipient@example.net"},
		[]byte("This is the email body."),
	)
	if err != nil {
		log.Fatal(err)
	}
}
```

## 链接

* [目录](https://github.com/MartialBE/the-way-to-go_ZH_CN/blob/master/eBook/directory.md)
* 上一节：[与 websocket 通信](/di-san-bu-fen-go-gao-ji-bian-cheng/15.0/15.11.md)
* 下一章：[常见的陷阱与错误](/di-si-bu-fen-shi-ji-ying-yong/16.0.md)
