Golang 发送html Gmail邮件

一、创建Gmail应用专用密码
官网教程
1.开启两步验证
2.创建应用专用密码入口
创建是app选customer,(注意不要选mail,否则就变成登录mail的密码,而不是代码发送邮件的密码)
二、实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//这里的body支持html的格式
func SendToMail(form, to, subject, body string) error {
    mailContent := fmt.Sprintf("To:%v\r\n"+
        "Subject: %v\r\n"+
        "Content-Type: text/html; charset=UTF-8\r\n\r\n "+
        "%v", to, subject, body)
    message := []byte(mailContent)

    host := "smtp.gmail.com:587"
    user := "发送的邮箱"
    password := "发送邮箱的密码"
    glog.Debug("host,user,password",host,user,password)
    hp := strings.Split(host, ":")
    auth := smtp.PlainAuth("", user, password, hp[0])
    send_to := strings.Split(to, ";")
    return smtp.SendMail(host, auth, form, send_to, message)
}