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) } }
有疑问加站长微信联系(非本文作者)