【问题标题】:Gmail API 'invalid username or password' when using OAuth2 in nodemailer在 nodemailer 中使用 OAuth2 时,Gmail API '无效的用户名或密码'
【发布时间】:2023-03-14 00:46:01
【问题描述】:

我正在尝试将 gmail smtp 与最新版本的 nodemailer 一起使用。 我已经完成了here 中描述的步骤。发送邮件时,我仍然收到以下错误消息:

错误:无效登录:535-5.7.8 用户名和密码不被接受

这很奇怪,因为我从不尝试使用密码/用户名登录,但我使用的是 OAuth2:

    transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            type: 'OAuth2',
            user: 'hello@company.com',
            clientId: '<clientId>.apps.googleusercontent.com',
            clientSecret: '<clientSecret>',
            accessToken: '<accessToken>',
            refreshToken: '<refreshToken>',
        }
    });

     transporter.sendMail({
        from: from,
        to: to,
        subject: subject,
        text: message,
        html: htmlMessage
    }, function (err, data) {
            if (err) {
                console.log(err);
                console.log("======");
                console.log(subject);
                console.log(message);
            } else {
                console.log('Email sent:');
                console.log(data);
            }
    });

有人知道我错过了什么吗?我尝试执行所有这些步骤来生成这些令牌 3 次,所以我很确定所有凭据都正确填写。

提前致谢

【问题讨论】:

    标签: node.js gmail-api nodemailer


    【解决方案1】:

    根据这个post,尝试如下配置您的传输器:

    const transporter = nodemailer.createTransport({
      host: 'smtp.gmail.com',
      port: 465,
      secure: true,
      auth: {
        type: 'OAuth2',
        user: process.env.MAIL_USER,
        clientId: process.env.GOOGLE_CLIENT_ID,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        refreshToken: process.env.GOOGLE_CLIENT_REFRESH_TOKEN
      }
    });
    

    如果您不确定如何生成 id、secret 和令牌,请按照此处的步骤操作https://medium.com/@pandeysoni/nodemailer-service-in-node-js-using-smtp-and-xoauth2-7c638a39a37e

    您也可以查看此link,了解您遇到该错误的可能原因。

    【讨论】:

    • 我很确定 id、secret 和 token 是按照官方 gmail API 文档正确生成的,并且那里的身份验证进展顺利。我看不出我在你的 sn-p 中所做的事情有什么不同?除了我也使用了 accesstoken,但即使没有我也会遇到同样的错误。我也遵循了这个指南:nodemailer.com/smtp/oauth2 总是“用户名和密码不被接受”,即使我没有提供。我会看看你提供的其他链接,无论如何谢谢!:)
    • @JC97 解决了吗?当我更改范围以使用完全权限时使用的范围似乎有问题,否则它不起作用。
    • 不,我们刚刚放弃使用 Google 并改用 Mailgun :)
    【解决方案2】:

    在我的情况下,将用户设置为只有我的用户名似乎很神奇!

    const transport = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        type: 'OAuth2',
        user: 'test', //Excluding the part after '@' Example: test@gmail.com to only 'test'
        clientId: CLIENT_ID,
        clientSecret: CLEINT_SECRET,
        refreshToken: REFRESH_TOKEN,
        accessToken: accessToken,
      },
    });
    

    【讨论】:

      猜你喜欢
      • 2019-01-30
      • 2015-05-31
      • 2016-08-22
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 2015-01-10
      • 2016-11-14
      • 1970-01-01
      相关资源
      最近更新 更多