GO使用SMTP发送邮件
核心代码:smtp.SendMail(host, auth, user, send_to, msg),auth := smtp.PlainAuth("", user, password, hp[0])
可行方案:使用企业邮箱的SMTP发送邮件,host :="smtp.exmail.qq.com:25",因此需要一个企业邮箱的账号和密码
直接上代码:
main.go
package main import ( "fmt" "net/smtp" "strings" ) func SendToMail(user, password, host, to, subject, body, mailtype string) error { hp := strings.Split(host, ":") auth := smtp.PlainAuth("", user, password, hp[0]) var content_type string if mailtype == "html" { content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8" } else { content_type = "Content-Type: text/plain" + "; charset=UTF-8" } msg := []byte("To: " + to + "\r\nFrom: " + user + ">\r\nSubject: " + "\r\n" + content_type + "\r\n\r\n" + body) send_to := strings.Split(to, ";") err := smtp.SendMail(host, auth, user, send_to, msg) return err } func main() { user := "yang**@yun*.com" password := "***" host := "smtp.exmail.qq.com:25" to := "397685131@qq.com" subject := "使用Golang发送邮件" body := ` <html> <body> <h3> "Test send to email" </h3> </body> </html> ` fmt.Println("send email") err := SendToMail(user, password, host, to, subject, body, "html") if err != nil { fmt.Println("Send mail error!") fmt.Println(err) } else { fmt.Println("Send mail success!") } }
遇到的问题:
1、body := ``,这里用的是反单引号,而非单引号;
2、err != nil,golang的nil在概念上和其它语言的null、None、nil、NULL一样,都指代零值或空值。nil是预先说明的标识符,也即通常意义上的关键字。在golang中,nil只能赋值给指针、channel、func、interface、map或slice类型的变量。如果未遵循这个规则,则会引发panic。对此官方有明确的说明:http://pkg.golang.org/pkg/builtin/#Type
3、参数auth,auth := smtp.PlainAuth("", user, password, hp[0])
4、强制类型转换,msg := []byte("To: " + to + "\r\nFrom: " + user + ">\r\nSubject: " + "\r\n" + content_type + "\r\n\r\n" + body)
5、多个邮箱:send_to := strings.Split(to, ";")
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。