Setup Nodemailer 2020
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
- Go to https://console.developers.google.com/
- Login or create a account
- Create a project and select it.
- Go to API & services → Credentials → Create Credentials → OAuth Client ID
- Choose web application
- Enter “https://developers.google.com/oauthplayground” in Authorized redirect URIs.
- Copy your client ID and client Secret.
Step 3: Get refresh_token
- Go to https://developers.google.com/oauthplayground/
- Go to right corner. Click on settings. Enter your client ID and client secret
- On left of page. Enter “ https://mail.google.com/” and click on Authorize APIs
- 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.