简体   繁体   English

如何解决 nodemailer 和 gmail 服务的“invalid_grant”错误?

[英]How to resolve "invalid_grant" error with nodemailer and gmail service?

I am running a MERN stack application which sends email using Nodemailer and Gmail service.我正在运行一个 MERN 堆栈应用程序,它使用 Nodemailer 和 Gmail 服务发送电子邮件。 Email notifications are sent during API calls.在 API 调用期间发送电子邮件通知。 The system has been live for 1 and a half years and they were never any issues with pushing email before.该系统已经上线 1 年半,之前推送电子邮件从来没有出现过任何问题。 However, as of yesterday I have been trying to diagnose this issue.但是,截至昨天,我一直在尝试诊断此问题。 Here is the error message:这是错误消息:

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] \}

Here is the code associated with nodemailer and setting up the client and transporter:下面是与 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
  }
});

Here is the code for sending mail inside an API call:这是在 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));

I think it has something to do with Google rejecting access tokens but I'm not sure why this would happen so randomly.我认为这与 Google 拒绝访问令牌有关,但我不确定为什么会如此随机地发生。

This is a critical application and I would appreciate any help I can get on this.这是一个关键的应用程序,如果我能在这方面获得任何帮助,我将不胜感激。

考虑更新 id, secret, refresh token ,因为它帮助我解决了同样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM