dtnpzghys01643322
2018-06-01 20:39
浏览 67
已采纳

Golang SMTP发送空电子邮件

Why when I try to send email i'm received empty email?

    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)
        }
    }

But if I change []byte(msg) to []byte("TEST") I received email with TEST word

图片转代码服务由CSDN问答提供 功能建议

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

  func contactHandler(w http.ResponseWriter,r * http.Request){
如果r.Method ==“ GET” {
t,_:= template.ParseFiles(“ template / static / contact.html”  )
 t.Execute(w,nil)
}否则,如果r.Method ==“ POST” {
 r.ParseForm()
 msg:=“名称:” + r.Form [“ name”]  [0] +“,电子邮件:” + r.Form [“电子邮件”] [0] +“,消息:” + r.Form [“消息”] [0] 
 println(“ out”,msg)\  n smtp.SendMail(“ smtp.gmail.com:587”,smtp.PlainAuth(“”,“ login”,“ password”,“ smtp.gmail.com”),“ sender@mail.com”,[]字符串 {“ me@mail.com”},[] byte(msg))
 http.Redirect(w,r,“ /”,301)
} 
} 
   \  n 
 

但是,如果我将 [] byte(msg)更改为 [] byte(“ TEST”),则我收到了包含测试字词的电子邮件 \ n

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drxm72811 2018-06-02 02:22
    已采纳

    You can't make up the email header format as you please. The email header must follow a specific format defined in RFC2822. Try to build your variable 'msg' by using this format:

    from := fmt.Sprintf("From: <%s>
    ", "sender@gmail.com")
    to := fmt.Sprintf("To: <%s>
    ", "recipient@gmail.com")
    subject := "Subject: This is the subject
    "
    body := "This is the email body.
    Bye
    "
    
    msg := from+to+subject+"
    "+body
    

    See details in https://tools.ietf.org/html/rfc2822

    点赞 评论

相关推荐 更多相似问题