Nodemailer Service in Node.js using SMTP and xoauth2

Soni Pandey
5 min readNov 25, 2019

--

Here, we will learn how to send a mail in Node.js using Nodemailer Package. What we are planning to use here:

  • Node.js
  • Express Framework
  • Nodemailer Package (version — “⁰.7.1”)

I assume, you all are aware with Node.js, Express Framework and Mongodb. If not, please have a look on my previous posts:

  1. Node.js Single File Application using Express Framework.
  2. CRUD Operations in Node.js Application (Expresss Framework) using mongodb.

These articles will atleast give you an overview about it.

What is Nodemailer Package? Send e-mails with Node.JS — easy as cake! Nodemailer Copyright © Nodemailer Here, we will create application which will do following things only:

  1. Nodemailer setup using SMTP (here you will use username and password).
  2. Nodemailer setup using xoauth2 (here you will need user, clientId, clientSecret, refreshToken, accessToken). Project Structure will be like this:
+ server
+ config
+ config.js
+ routes.js
+ server.js
+ package.json
+ README.md

Here, we don’t save data in database, so we are not using any database.

1. Setting up Server using Express Framework.

/**
* Module dependencies
*/
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = process.env.PORT || 3000
const router = express.Router()
app.use(router);
//load client folder
//bodyparser to use for request and respnse and set limit in request body data
router.use(bodyParser.urlencoded({ limit: '52428800', extended: true }));
router.use(bodyParser.json({limit: '52428800'}));
// Bootstrap routes
require('./server/config/routes')(router);
app.listen(port);
console.log('Express app started on port ' + port);

First of all, we required all the module dependencies. After that we used middleware instances body-parser, express.

2. Setting up Nodemailer using SMTP

const nodemailer = require('nodemailer')
const config = require('./config')
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport("SMTP", {
service: "Gmail",
auth: {
user: config.mailUser,
pass: config.mailPass
}
});
module.exports = function (app) {
// send mail with defined transport object
app.post('/send', function(req, res){
// setup e-mail data with unicode symbols
var mailOptions = {
from: ''+config.mailUser+'', // sender address
to: req.body.receivers, // list of receivers
subject: req.body.subject, // Subject line
text: req.body.text, // plaintext body
// html: '<b>Hello world 🐴</b>' // html body
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
return res.send(error);
}
return res.send("mail send successfully");
});
})
};

We need to install nodemailer 0.7.1 version as a dependency. To use Gmail you may need to configure “Allow Less Secure Apps” in your Gmail account unless you are using 2FA in which case you would have to create an Application Specific password. You also may need to unlock your account with ”Allow access to your Google account” to use SMTP. Copyright © Nodemailer

npm install nodemailer@0.7.1 -- save

and after that create transporter object using SMTP Transport. We are defined sender username and password in config file, you can change according to your gmail setup.

/**Add all configuration settings here*/
module.exports = {
mailUser: senderEmail,
mailPass: senderPass
}

We are parsing body data in mailOptions in this format:

{
"subject": "Nodemailer Test using SMTP",
"receivers": "sonipandey.71@gmail.com",
"text":"Hey, You Recieved message from your nodemailer package"
}

Transporter Object have one function named sendMail, which will send data using mailOptions. 3. Nodemailer setup using xoauth2. Here, transporter object will be change only

/**Module Dependency*/
const xoauth2 = require('xoauth2')
var smtpTransport = nodemailer.createTransport("SMTP",{
service:"Gmail",
auth:{
XOAuth2: {
user: config.mailUser,
clientId: config.clientId,
clientSecret: config.clientSecret,
refreshToken: config.refreshToken
}
}
});

We need to install xoauth2 and need to setup clientId, clientSecret and refreshToken.

Step I: Obtain OAuth 2.0 credentials at Google Developers Console. As stated here, you should:

  1. Go to the Google Developers Console.
  2. Select a project, or create a new one.
  3. In the sidebar on the left, expand APIs & auth. Next, click APIs. Select the Enabled APIs link in the API section to see a list of all your enabled APIs. Make sure that the “Gmail API” is on the list of enabled APIs. If you have not enabled it, select the Gmail API from the list of APIs (under Google Apps APIs), then select the Enable API button for the API.
  4. In the sidebar on the left, select Credentials.
  5. If you haven’t done so already, create your project’s OAuth 2.0 credentials by clicking Create new Client ID, and providing the information needed to create the credentials.
  1. Look for the Client ID and Client secret in the table associated with each of your credentials.

PAY SPECIAL ATTENTION TO specifying https://developers.google.com/oauthplayground as a Redirect URI when you create a new User in the console. Otherwise, you will have an error. Step II: Obtain the refresh token at Google OAuth2.0 Playground

  1. Go to the Google Oauth2.0 Playground.
  2. Click the Gear Button on the right-top. Set your Client ID and Client Secret obtained from theGoogle Developers Console, and select Access token location as Authorization header w/ Bearer prefix. Close this configuration overlay.
  1. Set up the scopes. Use https://mail.google.com/ as it’s the one need by nodemailer. Then click the Authorize APIs button.
  1. After OAuth2.0 authorization, exchange authorization code for tokens and your refresh token is ready-to-use.

and setup your configuration here:

/**Add all configuration settings here*/
module.exports = {
mailUser: senderEmail,
mailPass: senderPass
clientId: clientId,
clientSecret: clientSecret,
refreshToken: refreshToken
}

Feel free to clone the full code for this post to see the full picture of how everything works together and customize it for your own needs and mark it starred, if it useful. Have a look to repository for complete working code. source code on github You can reach out to me for any doubt and suggestions. Please share this with others as well.

Thanks!
Happy Coding!!

--

--

Soni Pandey
Soni Pandey

Written by Soni Pandey

I am a Node.js Developer and eager to learn new technology. I blog, tweet & read whenever I can.

No responses yet