[英]How to resolve "invalid_grant" error with nodemailer and gmail service?
我正在運行一個 MERN 堆棧應用程序,它使用 Nodemailer 和 Gmail 服務發送電子郵件。 在 API 調用期間發送電子郵件通知。 該系統已經上線 1 年半,之前推送電子郵件從來沒有出現過任何問題。 但是,截至昨天,我一直在嘗試診斷此問題。 這是錯誤消息:
Transporter set up
[0] Error: invalid_grant
[0] at D:\Dev\Projects\pro-optics\pro-optics\node_modules\nodemailer\lib\xoauth2\index.js:259:33
[0] at PassThrough.<anonymous> (D:\Dev\Projects\pro-optics\pro-optics\node_modules\nodemailer\lib\xoauth2\index.js:328:20)
[0] at Object.onceWrapper (events.js:312:28)
[0] at PassThrough.emit (events.js:223:5)
[0] at endReadableNT (_stream_readable.js:1185:12)
[0] at processTicksAndRejections (internal/process/task_queues.js:81:21) {
[0] code: 'EAUTH',
[0] command: 'AUTH XOAUTH2'
[0] \}
下面是與 nodemailer 相關的代碼,並設置客戶端和傳輸器:
const nodemailer = require('nodemailer');
const { google } = require('googleapis');
// Setting up OAuth2
const OAuth2 = google.auth.OAuth2;
const oauth2Client = new OAuth2(
clientId,
clientSecret,
'https://developers.google.com/oauthplayground'
);
oauth2Client.setCredentials({
refresh_token: refreshToken
});
let accessToken;
oauth2Client
.refreshAccessToken()
.then(tokens => (accessToken = tokens.credentials.access_token));
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user,
clientId,
clientSecret,
refreshToken,
accessToken
},
tls: {
rejectUnauthorized: false
}
});
這是在 API 調用中發送郵件的代碼:
// Prepare email
const emailContent = getTicketTemplate(ticket, true, true);
console.log('Transporter set up');
let mailOptions = {
from: `"Pro Optics" <${user}>`,
to: recipients,
subject: `[OFFICIAL] Ticket Report: INTV ${ticket._id} ✔`,
html: emailContent
};
transporter
.sendMail(mailOptions)
.then(info => console.log(info))
.catch(error => console.log(error));
我認為這與 Google 拒絕訪問令牌有關,但我不確定為什么會如此隨機地發生。
這是一個關鍵的應用程序,如果我能在這方面獲得任何幫助,我將不勝感激。
考慮更新 id, secret, refresh token ,因為它幫助我解決了同樣的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.