英文:
go package smtp doesn't showing message body on email
问题
在你提供的代码中,邮件的内容是通过拼接字符串的方式生成的。根据你的描述,邮件成功发送到了Gmail收件箱,但是邮件的内容为空。根据代码分析,可能是拼接字符串时出现了问题。
为了解决这个问题,你可以检查以下几点:
-
确保
body
变量中的内容不为空。你可以在调用SendEmail
函数之前打印body
的值,确保它包含了预期的验证码信息。 -
检查
from
、to
、subject
和body
变量中是否包含特殊字符或换行符。这些字符可能会干扰邮件的格式,导致邮件内容为空。你可以尝试移除这些特殊字符或使用合适的转义字符。 -
确保
message
变量中的每行都以换行符\n
结尾。这是邮件头部和正文之间的分隔符,确保每行都以换行符结束可以保证邮件内容正确显示。
如果以上步骤都没有解决问题,你可以尝试使用其他方法来构建邮件内容,例如使用bytes.Buffer
或模板引擎来生成邮件内容。这些方法可以更灵活地处理字符串拼接的问题。
希望这些建议对你有帮助!如果还有其他问题,请随时提问。
英文:
So, I want to send an email message. The email was successfully sent to the Gmail inbox, but the message or body is missing or empty. Here's the code
package helper
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))
}
Package main
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()
}
in the below code in the helper package, it already exists and has been used as a parameter in smtp.SendMail(), but still the email doesn't have a message or is empty
message := "From: "+ from + "\n" +
"To: " + to + "\n" +
"Subject: " + subject + "\n" +
body
How to fix it?
答案1
得分: 0
body := "您的验证码是:" + code
message := "发件人:" + from + "\n" +
"收件人:" + to + "\n" +
"主题:" + subject + "\n\n" +
body
在消息头和消息正文之间需要有一个空行,这里缺少了。
一些邮件服务器会在任何看起来不像是头部的内容之前添加这一行,一些邮件服务器会以其他方式修复这个问题,一些服务器会接受这封邮件,但显示可能会出现问题,而一些服务器会直接拒绝这封格式错误的邮件。
有关邮件的预期格式,请参阅RFC 5322。
英文:
> body := "Your verification code is: "+code
>
> message := "From: "+ from + "\n" +
> "To: " + to + "\n" +
> "Subject: " + subject + "\n" +
> body
There need to be an empty line between message header and message body which is missing here.
Some mail server will fix this by adding this line before anything which does not look like a header, some mail servers will fix this in some other ways, some servers accept this mail as it is but display will somehow fail and some reject this malformed mail directly.
For more on how a mail is expected to look like see RFC 5322.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论