Skip to content

Latest commit

 

History

History
82 lines (71 loc) · 2.16 KB

15.12.md

File metadata and controls

82 lines (71 loc) · 2.16 KB

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

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("[email protected]")
	client.Rcpt("[email protected]")
	// 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 作为邮件内容,发出一封邮件:

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

示例 15.27 smtp_auth.go

package main

import (
	"log"
	"net/smtp"
)

func main() {
	// Set up authentication information.
	auth := smtp.PlainAuth(
		"",
		"[email protected]",
		"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,
		"[email protected]",
		[]string{"[email protected]"},
		[]byte("This is the email body."),
	)
	if err != nil {
		log.Fatal(err)
	}
}

链接