为什么当我尝试发送电子邮件时收到的是空电子邮件?
func contactHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, _ := template.ParseFiles("template/static/contact.html")
t.Execute(w, nil)
} else if r.Method == "POST" {
r.ParseForm()
msg := "Name: " + r.Form["name"][0] + ", Email: " + r.Form["email"][0] + ", Message: " + r.Form["message"][0]
println("out ", msg)
smtp.SendMail("smtp.gmail.com:587", smtp.PlainAuth("", "login", "password", "smtp.gmail.com"), "sender@mail.com", []string{"me@mail.com"}, []byte(msg))
http.Redirect(w, r, "/", 301)
}
}
但是如果我将 []byte(msg)
更改为 []byte("TEST")
我会收到带有 TEST 词的电子邮件
最佳答案
您不能随心所欲地编写电子邮件 header 格式。电子邮件 header 必须遵循 RFC2822 中定义的特定格式。尝试使用以下格式构建变量“msg”:
from := fmt.Sprintf("From: <%s>\r\n", "sender@gmail.com")
to := fmt.Sprintf("To: <%s>\r\n", "recipient@gmail.com")
subject := "Subject: This is the subject\r\n"
body := "This is the email body.\r\nBye\r\n"
msg := from+to+subject+"\r\n"+body
关于Golang SMTP 发送空邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50650719/