javascript - 为什么我收到错误“无法生成令牌。使用 Nodemailer 时检查您的身份验证选项?
问题描述
我看到几个关于正常 OATH 的类似问题。但是,我决定尝试支持 gmail 服务帐户的 nodemailers 新功能。我一遍又一遍地遇到同样的错误,并且不知道如何解决它。有没有人有任何见解?
第 1 步:我从我的项目中设置了我的服务帐户。然后我下载了 key.json 文件。
第 2 步:我去了 GCP API 并为我的项目启用了 gmail api。然后我验证了我的新服务帐户在列表中。(我不想发布图片,因为它包含敏感信息。但我三次检查它是否在为 gmail api 启用的服务帐户列表中。
第三步:我写了一点代码。
return Promise.resolve()
.then(() => {
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: <service account email>,
serviceClient: <service account client>,
privateKey: <Private key> (including the \n at the end),
},
});
})
.then(() => {
const mailOptions = {
from: '"Support" support@myapp.com',
to: targetEmail,
subject: 'My Subject',
html: 'My super support email'
};
return mailTransport.sendMail(mailOptions);
})
.catch(err => {
console.error(err);
})
我打印了一个很棒的错误,上面写着
Error { Error: Can't generate token. Check your auth options
at SMTPConnection._handleXOauth2Token (/workspace/node_modules/nodemailer/lib/smtp-connection/index.js:1697:27)
at SMTPConnection.login (/workspace/node_modules/nodemailer/lib/smtp-connection/index.js:540:22)
at XOAuth2.generateToken (/workspace/node_modules/nodemailer/lib/xoauth2/index.js:170:33)
at XOAuth2.getToken (/workspace/node_modules/nodemailer/lib/xoauth2/index.js:123:18)
at connection.connect (/workspace/node_modules/nodemailer/lib/smtp-transport/index.js:374:32)
at SMTPConnection.once (/workspace/node_modules/nodemailer/lib/smtp-connection/index.js:215:17)
at Object.onceWrapper (events.js:286:20)
at SMTPConnection.emit (events.js:198:13)
at SMTPConnection.EventEmitter.emit (domain.js:466:23)
at SMTPConnection._actionEHLO (/workspace/node_modules/nodemailer/lib/smtp-connection/index.js:1313:14) code: 'EAUTH', command: 'AUTH XOAUTH2' }
有谁知道我做错了什么?
注意:有关更多上下文。这在 firebase 函数内部运行。
解决方案
我刚刚遇到了同样的问题,我在这里找到了解决方案:
如教程中所述,您必须获取刷新令牌。
在 Google API 控制台中的 OAuth 凭据中,提供https://developers.google.com/oauthplayground/作为重定向 URI。
转到https://developers.google.com/oauthplayground/页面。
在设置菜单的右上角选择“使用您自己的 OAuth 凭据”并提供您的凭据。
然后在“选择和授权 API”部分提供链接https://mail.google.com并单击“授权 API”按钮。
最后用授权码交换令牌。
当您拥有刷新令牌时,您可以在配置中传递它:
{
service: 'gmail',
auth: {
type: 'OAuth2',
user: USER_EMAIL_ADDRESS,
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
refreshToken: REFRESH_TOKEN,
},
}
根据这个答案,谷歌的刷新令牌不会过期:
此致,
彼得
推荐阅读
- java - 如何正确迁移到 Realm 中的嵌入式对象?
- python - 如果变量没有,如何将备用值分配给变量
- css - 修改 GTK 按钮样式/CSS 并立即更新/刷新
- jenkins - 如何在詹金斯管道脚本上禁用轻量级结帐?
- winapi - 如何在 Win32 API 中重现资源管理器按钮
- powershell - 递归地将文件从所有子文件夹移动到目录中的一个子文件夹
- python - Django read file from model, [Errno 2] No such file or directory
- keras - 使用 Keras Tuner 进行超参数调优
- node.js - 如何从 MongoDb 获取云 URL 数据
- php - 为什么我的 where 没有只发送对应关系?