在 Nodemailer 中使用 OAuth2 时 Gmail API“用户名或密码无效”

JC9*_*C97 5 node.js nodemailer gmail-api

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

错误:无效登录: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);
            }
    });
Run Code Online (Sandbox Code Playgroud)

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

提前致谢

abi*_*ita 3

根据这篇文章,尝试配置您的传输器,如下所示:

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
  }
});
Run Code Online (Sandbox Code Playgroud)

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

您还可以检查此链接,了解遇到该错误的可能原因。