Search code examples
node.jsemailgmailgoogle-oauth

Trying to use nodemailer to send emails using gmail and am receiving the error: "Can't create new access token for user"


I currently have a setup to send emails using nodemailer from gmail. It works correctly when I manually create an access token (which only last for ~1 hour). However, after that hour has passed I get the below error. Note, during that hour I am able to send emails just fine and everything works.

 { Error: Can't create new access token for user
at XOAuth2.generateToken (C:\Users\user\My-Projects\***\node_modules\nodemailer\lib\xoauth2\index.js:162:33)
at XOAuth2.getToken (C:\Users\user\My-Projects\***\node_modules\nodemailer\lib\xoauth2\index.js:111:18)
at SMTPConnection._handleXOauth2Token (C:\Users\user\My-Projects\***\node_modules\nodemailer\lib\smtp-connection\index.js:1421:27)
at Immediate.setImmediate (C:\Users\user\My-Projects\***\node_modules\nodemailer\lib\smtp-connection\index.js:1239:45)
at runCallback (timers.js:666:20)
at tryOnImmediate (timers.js:639:5)
at processImmediate [as _immediateCallback] (timers.js:611:5) code: 'EAUTH', command: 'AUTH XOAUTH2' }

The code I am using to send the email is:

var emailMsg = `Name: ${name}\nEmail: ${email}\n\nMessage:\n${msg}`;

var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        type: 'OAuth2',
        user: process.env.GMAIL_ACC,
        clientId: process.env.GMAIL_CLIENTID,
        clientSecret: process.env.GMAIL_CLIENTSECRET,
        refreshToken: process.env.GMAIL_RFRESHTOKEN,
        accessToken: process.env.GMAIL_ACCESSTOKEN
    }
});

var mailOptions = {
    from: process.env.GMAIL_ACC,
    to: process.env.GMAIL_ACC,
    subject: `Contact Form - ${name}`,
    text: emailMsg
};

transporter.sendMail(mailOptions,
    function(mailErr, mailRes) {
        if(mailErr) {
            //Mail was unable to send
            sendResponse(418, false, [{'email': 'Server was unable to send email.'}]);
            console.log('Mail Error:\n ', mailErr);
        } else {
            //Everything worked correctly. (As far as responses go)
            sendResponse(200, true);
        }
    }
);

Things I have tried: - Allowing less secure apps (Doesn't seem to have any affect) - Disabling AntiVirus (This was originally a problem for something unrelated) - Creating a new app and set of tokens (This has had 0 affect)

Any help would be appreciated, thanks!


Solution

  • process.env.GMAIL_RFRESHTOKEN - Should this be GMAIL_REFRESH_TOKEN? Looking through the source code of the library, it would appear this error would be thrown directly from the GMail API, as the library never constructs this error itself. This would support the theory that the refresh token is undefined/null.