Search code examples
emailgogmail

smtp error: 535 5.7.8 Username and Password not accepted for gmail in go


I'm trying to test an app's outgoing emails from localhost using this function:

func SendContactUsForm(subject, email, body string) error {
    var err error
    from := "mysender@gmail.com"
    pass := "somecrazypw"
    to := "mydestination@gmail.com"
    msg := "From: " + from + "\n" +
    "To: " + to + "\n" +
    "Subject: Contact form:" + subject + "\n" + body
    err = smtp.SendMail("smtp.gmail.com:587",
        smtp.PlainAuth("", from, pass, "smtp.gmail.com"),
        from, []string{to}, []byte(msg))
    if err != nil {
        log.Printf("smtp error: %s", err)
        return err
    }
    return nil
}

But I get this error:

send_emails.go:171: smtp error: 535 5.7.8 Username and Password not accepted. Learn more at 5.7.8 https://support.google.com/mail/?p=BadCredentials a7sm5381413wmh.14 - gsmtp contact.go:38: error seding contact us form 535 5.7.8 Username and Password not accepted.

Despite the fact that the credentials of mysender@gmail.com are correct and I have enabled Allow less secure apps on mysender@gmail.com.

So what could be wrong here? And how can I fix it?


Solution

  • Enable the 2FA (2 Step Verification) authentication: myaccount.google.com/security if not already

    Generate a password from https://security.google.com/settings/security/apppasswords and use that password instead.

    An App Password is a 16-digit passcode that gives an app or device restricted access to your Google Account without having to divulge your personal password and complete access to your Google Account.

    More details on how to generate one!