Setup Nodemailer 2020

Tanuj Choudhary
2 min readNov 8, 2020

This tutorial shows how to setup nodemailer and send mails using node js.

Prerequisites:

  • Node js
  • Basic knowledge of Google Console

Step 1: Create a simple node or express server

Step 2: Create Client ID in Google Console

Step 3: Get refresh_token

  • Click “Exchange authorization code for tokens” button.
  • Congrats! You got your refresh token

Step 4: Lets see the code

  • Open your terminal in project directory and run
npm install googleapis
  • Create a file named oAuth2Client.js
const { google } = require('googleapis');
const { OAuth2 } = google.auth;// Reusable clientconst oAuth2Client = new OAuth2(
'Your Client ID',
'Your Client Secret',
'https://developers.google.com/oauthplayground'
);
oAuth2Client.setCredentials({
refresh_token: 'Your refresh token',
});
module.exports = oAuth2Client;
  • Create a file named nodemailer.js
const nodemailer = require('nodemailer');const oAuth2Client = require('./oAuth2Client');
const accessToken = oAuth2Client.getAccessToken();const smtpTransport = nodemailer.createTransport({service: 'gmail',auth: {type: 'OAuth2',user: 'Your OAuth Email', // Your gmail addressclientId: 'Your Client ID',clientSecret: 'Your Client Secret',refreshToken: 'Your OAuth refresh token',accessToken: accessToken,},});module.exports = smtpTransport;
  • Import nodemailer in file where you want to use it
const nodemailer = require('./nodemailer');// Mail options
const mailOptions = {
from: 'SENDER_EMAIL',
to: 'RECEIVER_EMAIL',
subject: 'YOUR_SUBJECT',
text: 'YOUR_MESSAGE',
};
// Send mail
nodemailer.sendMail(mailOptions, () => {} );
// Close
nodemailer.close();

That's it.

Thanks for reading.

--

--