下面使用go来发送邮件
注意
1、body := ``,这里用的是反单引号,而非单引号; 2、err != nil,golang的nil在概念上和其它语言的null、None、nil、NULL一样,都指代零值或空值。 nil是预先说明的标识符,也即通常意义上的关键字。在golang中,nil只能赋值给指针、channel、func、 interface、map或slice类型的变量。如果未遵循这个规则,则会引发panic。对此官方有明确的说明: 3、参数auth,auth := smtp.PlainAuth("", user, password, hp[0]) 4、强制类型转换,msg := []byte("To: " + to + "\r\nFrom: " + user + "\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body) 5、多个邮箱:send_to := strings.Split(to, ",") 6、如果发送不成功,注意是否要使用授权码作为密码来发送
下面是一个测试通过的示例
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: " + subject + "\r\n" + content_type + "\r\n\r\n" + body) fmt.Println(string(msg)) send_to := strings.Split(to,",") err := smtp.SendMail(host, auth, user, send_to, msg) return err } func main() { user := "a@b.com" password := "aaa" host := "smtp.ym.163.com:25" to := "b@b.com,c@b.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!") } } D:\go\test2>go run main.go send email To: b@b.com,c@b.com From: a@b.com Subject: 使用Golang发送邮件 Content-Type: text/html; charset=UTF-8 <html> <body> <h3> "Test send to email" </h3> </body> </html> Send mail success!
如果想要发送漂亮的html页面,可以从下面的站点获取html文件,然后将源码放到上面的body中就可以
https://mp.weixin.qq.com/s?__biz=MzI4NjczNzAxNQ==&mid=2247483680&idx=1&sn=fc66daa5434aaaaee05590b07dca926b&chksm=ebd91638dcae9f2e1b155911c78ccc90a4131c9701a74d87ed8c3e0b14b18e6b742f7dd79677&scene=0#rd
参考文档:
https://studygolang.com/articles/2098
http://blog.csdn.net/wangshubo1989/article/details/70808989
–
–
–
评论前必须登录!
注册