Golang使用Gomail发送Gmail邮件失败的解决方法

Golang使用Gomail发送Gmail邮件失败的解决方法 我正在尝试使用这个模块:

我放入了在这里找到的示例代码:

  • PREFIX pkg.go.dev/gopkg.in/gomail.v2#example-package

PREFIX=https://

我更改了:

d := gomail.NewDialer(“smtp.example.com”, 587, “user”, “123456”)

将 “example” 改为 “gmail”,并且用户名和密码是正确的。我还尝试将 587 改为 465。

两种方法都不行。我收到错误: panic: 535 5.7.8 用户名和密码未被接受。更多信息,请访问 5.7.8 PREFIX support . google . com / mail / ?p=BadCredentials 6a1803df08f44-6c340bfa70asm21454206d6.12 - gsmtp

我需要做什么来修复它?


更多关于Golang使用Gomail发送Gmail邮件失败的解决方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

如果你百分之百确定所有数据都是正确的,但仍然收到相同的错误信息,我建议尝试使用另一个电子邮件库进行测试。go-gomail/gomail 的最后一次提交已经是 8 年前了。

我推荐 go-mail。

GitHub - wneessen/go-mail: 📧 Easy to use, yet comprehensive library for...

更多关于Golang使用Gomail发送Gmail邮件失败的解决方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


对于我来说,使用下面的代码,邮件成功发送了(在替换了所有的“XXX”之后):

package main

import (
    "gopkg.in/gomail.v2"
)

func main() {
    d := gomail.NewDialer("smtp.gmail.com", 587, "XXX@gmail.com", "XXX")
    msg := gomail.NewMessage()
    msg.SetHeader("From", "XXX@gmail.com")
    msg.SetHeader("To", "XXX")
    msg.SetHeader("Subject", "does gopkg.in/gomail.v2 work with gmail?")
    msg.SetBody("text/plain", "yes, it does!")
    _ = d.DialAndSend(msg)
}

你确定你的凭据是正确的吗?

你的账户是否开启了双重验证? 你是否设置了应用专用密码

或者你正在使用你的谷歌账户密码? 这对于SMTP是行不通的。

问题在于Gmail的安全设置。从2022年5月起,Gmail不再支持仅使用用户名和密码通过SMTP发送邮件。你需要使用应用专用密码或OAuth 2.0。

解决方案1:使用应用专用密码(推荐)

  1. 启用Google账户的两步验证
  2. 生成应用专用密码:
package main

import (
    "gopkg.in/gomail.v2"
)

func main() {
    m := gomail.NewMessage()
    m.SetHeader("From", "your-email@gmail.com")
    m.SetHeader("To", "recipient@example.com")
    m.SetHeader("Subject", "Hello!")
    m.SetBody("text/plain", "This is the email body.")

    // 使用应用专用密码,不是你的Gmail密码
    d := gomail.NewDialer("smtp.gmail.com", 587, "your-email@gmail.com", "your-16-digit-app-password")

    if err := d.DialAndSend(m); err != nil {
        panic(err)
    }
}

解决方案2:使用OAuth 2.0(更安全)

package main

import (
    "context"
    "encoding/base64"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "google.golang.org/api/gmail/v1"
    "google.golang.org/api/option"
)

func sendEmailWithOAuth() error {
    ctx := context.Background()
    
    // 配置OAuth 2.0
    config := &oauth2.Config{
        ClientID:     "your-client-id",
        ClientSecret: "your-client-secret",
        RedirectURL:  "urn:ietf:wg:oauth:2.0:oob",
        Scopes:       []string{gmail.GmailSendScope},
        Endpoint:     google.Endpoint,
    }
    
    // 获取token(首次需要授权)
    token := &oauth2.Token{
        AccessToken:  "your-access-token",
        RefreshToken: "your-refresh-token",
        TokenType:    "Bearer",
    }
    
    srv, err := gmail.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token)))
    if err != nil {
        return err
    }
    
    // 创建邮件
    var message gmail.Message
    emailTo := "recipient@example.com"
    msgStr := []byte(
        "From: your-email@gmail.com\r\n" +
        "To: " + emailTo + "\r\n" +
        "Subject: Test Email\r\n\r\n" +
        "This is a test email.")
    
    message.Raw = base64.URLEncoding.EncodeToString(msgStr)
    
    // 发送邮件
    _, err = srv.Users.Messages.Send("me", &message).Do()
    return err
}

解决方案3:使用支持OAuth的SMTP库

package main

import (
    "github.com/emersion/go-sasl"
    "github.com/emersion/go-smtp"
)

func sendWithXOAuth2() error {
    auth := sasl.NewXOAuth2Client("your-email@gmail.com", "your-access-token")
    
    to := []string{"recipient@example.com"}
    msg := []byte("To: recipient@example.com\r\n" +
        "Subject: Test\r\n\r\n" +
        "This is the email body.")
    
    err := smtp.SendMail("smtp.gmail.com:587", auth, "your-email@gmail.com", to, msg)
    return err
}

端口配置说明:

  • 端口587:使用STARTTLS(推荐)
  • 端口465:使用SSL/TLS
  • 确保防火墙允许出站连接到这些端口

检查事项:

  1. 确认已启用两步验证
  2. 使用应用专用密码而非账户密码
  3. 检查账户是否启用了"安全性较低的应用访问"(不推荐)
  4. 确保网络可以访问Gmail SMTP服务器

最常见的错误是直接使用Gmail密码而不是应用专用密码。生成应用专用密码后,问题通常可以解决。

回到顶部