golang:send mail using smtp package

时间:2021-09-30 08:40:35

go语言发送邮件,可以使用smtp包,两个关键函数:

func PlainAuth(identity, username, password, host string) Auth

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

刚开始玩的时候,很好奇邮件的title是怎么设置进去的,毕竟从代码没看见有setTitle。后来发现是解析msg获取标题、发件人、收件人、邮件格式、邮件内容等;因此msg需要按一定格式写:To: xxx\r\nFrom:xxxx\r\nSubject: xxxx\r\nContent-Type:text/html; charset=UTF-8\r\n\r\n[邮件内容]

func (this *TestController) SendMail(){

    subject := "This is golang test email..."
user := "xxxxx@163.com"
to := []string {"xxxxx@163.com"}
nickname := "dyao"
content := "mail body....."
contentType := "Content-Type: text/html; charset=UTF-8"
msg := []byte("To: " + strings.Join(to, ",") + "\r\nFrom: " + nickname + "<" + user + ">\r\nSubject: " + subject + "\r\n" + contentType + "\r\n\r\n" + content) auth := smtp.PlainAuth(
"",
user,
"testpassword",
"smtp.163.com",
) err := smtp.SendMail(
"smtp.163.com:25",
auth,
user,
to,
[]byte(msg),
)
if err != nil{
log.Fatal(err)
}else {
log.Printf("Mail send:\r\n%s", msg)
}
}

===================2018/01/18=======================

163邮箱,把发送的邮件当垃圾拦截了,今天打算换qq邮箱,被坑到怀疑人生....

密码,不是qq登陆密码,是授权码!授权码!授权码!授权码!

授权码,在qq邮箱设置里面获取,会发送到手机上