Golang SMTP 发送空邮件

标签 go smtp

为什么当我尝试发送电子邮件时收到的是空电子邮件?

    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

详见 https://www.rfc-editor.org/rfc/rfc2822

关于Golang SMTP 发送空邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50650719/

相关文章:

Notepad++ 的Go语言插件

go - 为什么不能加载golang/protobuf/proto

c# - 使用 System.Net.Mail 通过谷歌发送 smtp 邮件让我超时异常

php - Apache 用户无法连接到 smtp (Centos)

http - 使用 mime/multipart 上传会损坏文件

c - 使用 golang 的 Windows Hook

Go lib/pq 打开方法返回未定义的 : time. 直到

git - 使用git send-email时出现 "Unable to initialize SMTP properly."如何解决?

python - App Engine 开发服务器 sendmail 错误 - 想要抑制

node.js - 我如何使用 Loopback.io 设置 SMTP