php小編子墨提醒大家在使用Go語言的smtp包發送電子郵件時可能會遇到一個問題,即消息正文在郵件中未被正確顯示的情況。這個問題可能導致郵件無法正常傳達所需的信息。在解決這個問題之前,讓我們先了解一下smtp包的使用方法以及可能的原因。
問題內容
所以,我想發送一封電子郵件。電子郵件已成功發送到 gmail 收件箱,但郵件或正文丟失或為空。這是代碼
包助手
func randomstringbytes() string {
rand.seed(time.now().unixnano())
number := []byte("0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz")
b := make([]byte, 6)
for i := range b{
b[i] = number[rand.intn(len(number))]
}
return string(b)
}
func sendemail(to string, code string) error {
from := "xxx"
password := "xxx"
smptserver := "smtp.gmail.com:587"
subject := "verification code"
body := "your verification code is: "+code
message := "from: "+ from + "\n" +
"to: " + to + "\n" +
"subject: " + subject + "\n" +
body
auth := smtp.plainauth("", from, password, "smtp.gmail.com")
return smtp.sendmail(smptserver, auth, from, []string{to}, []byte(message))
}
登錄后復制
包主
func emailverify() {
email := "xxx"
code := helper.randomstringbytes()
fmt.println("code:", code)
err := helper.sendemail(email, code)
if err != nil {
fmt.println("error sending email:", err)
return
}
}
func main(){
emailverify()
}
登錄后復制
在幫助程序包中的以下代碼中,它已經存在并已在 smtp.sendmail() 中用作參數,但電子郵件仍然沒有消息或為空
message := "From: "+ from + "\n" +
"To: " + to + "\n" +
"Subject: " + subject + "\n" +
body
登錄后復制
如何解決?
解決方法
body := "Your verification code is: "+code message := "From: "+ from + "\n" + "To: " + to + "\n" + "Subject: " + subject + "\n" + body
登錄后復制
消息頭和消息正文之間需要有一個空行,但此處缺少。
一些郵件服務器會通過在任何看起來不像標題的內容之前添加此行來解決此問題,一些郵件服務器會以其他方式解決此問題,一些服務器按原樣接受此郵件,但顯示會以某種方式失敗,有些服務器會拒絕直接發送此畸形郵件。
有關郵件預期外觀的更多信息,請參閱 rfc 5322。






