Using OAuth2

If a XOAuth2 token generator is used as the value for auth.xoauth2 when setting up transporter object then you do not need to set the value for user or pass as OAuth2 is used for authenticated.

XOAuth2 generator generates required accessToken itself if it is missing or expired. If authentication fails, a new token is requested and the authentication is retried once. If it still fails, an error is returned.

Install xoauth2 module to use XOauth2 token generators (not included by default)

npm install xoauth2 --save

Example

var nodemailer = require('nodemailer');
var xoauth2 = require('xoauth2');

// listen for token updates (if refreshToken is set)
// you probably want to store these to a db
generator.on('token', function(token){
    console.log('New token for %s: %s', token.user, token.accessToken);
});

// login
var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        xoauth2: xoauth2.createXOAuth2Generator({
            user: '{username}',
            clientId: '{Client ID}',
            clientSecret: '{Client Secret}',
            refreshToken: '{refresh-token}',
            accessToken: '{cached access token}'
        })
    }
});

Troubleshooting

  • The correct OAuth2 scope for Gmail is "https://mail.google.com/", make sure your client has this scope set