Files
the-way-to-go_ZH_CN/eBook/15.12.md
marjune 9be772e9bb Add chapter 17.x (#697)
* improve chapter 15.12

* add chapter 17.2

* add chapter 17.3

* add chapter 17.4
2019-07-27 19:26:44 -07:00

83 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 15.12 用 smtp 发送邮件
`smtp` 包实现了用于发送邮件的“简单邮件传输协议”Simple Mail Transfer Protocol。它有一个 `Client` 类型,代表一个连接到 SMTP 服务器的客户端:
- `Dial` 方法返回一个已连接到 SMTP 服务器的客户端 `Client`
- 设置 `Mail`from即发件人`Rcpt`to即收件人
- `Data` 方法返回一个用于写入数据的 `Writer`,这里利用 `buf.WriteTo(wc)` 写入
示例 15.26 [smtp.go](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](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)
}
}
```
## 链接
- [目录](directory.md)
- 上一节:[与 websocket 通信](15.11.md)
- 下一章:[常见的陷阱与错误](16.0.md)