Search code examples
gosmtp

go package smtp doesn't showing message body on email


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?


Solution

  • 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.