如何使用go发送邮件?
一、代码实现
(1)直接上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
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) send_to := strings.Split(to, ";") err := smtp.SendMail(host, auth, user, send_to, msg) return err } func main() { user := "**********@qq.com" password := "***********" host := "smtp.qq.com:25" to := "***********@qq.com" subject := "test golang mail" body := ` <html> <body> <h3> "go 邮件测试" </h3> </body> </html> ` fmt.Println("sending 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!") } } |
简单直观。
(2)遇到的一些问题
1.body :=
这里用的是反单引号,不是单引号!
2.auth
1 |
auth := smtp.PlainAuth("", user, password, hp[0]) |
3.内容需要强制类型转换为byte才能进行传输
1 |
msg := []byte("To: " + to + "\r\nFrom: " + user + ">\r\nSubject: " + "\r\n" + content_type + "\r\n\r\n" + body) |
4.如果需要群发多个邮箱:
1 |
send_to := strings.Split(to, ";") |
或者自己写个循环进行群发.
二、总结
记录一下。