I've set up Nodemailer to work with Gmail using OAuth2. It works fine until the access token expires. At this point, despite having a refresh token, I get the following error message:
{
Error: Invalid status code 401
at ClientRequest.req.on.res (xxxxxxxxxxx)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:191:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:522:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:411:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at TLSSocket.Readable.push (_stream_readable.js:136:10)
at TLSWrap.onread (net.js:561:20)
type: 'FETCH',
sourceUrl: 'https://accounts.google.com/o/oauth2/token',
code: 'EAUTH',
command: 'AUTH XOAUTH2'
}
Here's my code. I've also tried including the refresh token and access token in the initial nodemailer setup, as well as including the expiry date. Each time I get the same result.
Nodemailer setup:
const nodemailer = require('nodemailer')
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
clientId: 'xxxxxxxxxx',
clientSecret: 'xxxxxxxxxx'
}
});
transporter.on('token', token => {
console.log('A new access token was generated');
console.log('User: %s', token.user);
console.log('Access Token: %s', token.accessToken);
console.log('Expires: %s', new Date(token.expires));
});
E-mail setup:
const mailOptions = {
from: xxxxxxxxx,
to: xxxxxxxxx,
subject: 'Test Subject',
text: 'This is a test',
html: '<p>This is a test</p>',
auth: {
user: 'xxxxxxxxxxxx',
refreshToken: 'xxxxxxxxxxxxx',
accessToken: 'xxxxxxxxxxxxx'
}
}
E-mail send
transporter.sendMail(mailOptions, function(err, info){
if(err){
return console.log(err);
}
console.log('Message %s sent: %s', info.messageId, info.response)
})
Can anyone suggest what may be going wrong?