I am running a MERN stack application which sends email using Nodemailer and Gmail service. Email notifications are sent during API calls. The system has been live for 1 and a half years and they were never any issues with pushing email before. 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:
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:
// 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.
This is a critical application and I would appreciate any help I can get on this.