Learn Nodemailer Module in Node.js

Read it in 7 Mins

Last updated on
16th Apr, 2021
Published
03rd Jul, 2020
Views
6,987
Learn Nodemailer Module in Node.js

In this tutorial, we will learn how to send email in Node.js using the nodemailer npm package.

For the email provider, we are going to use Sendinblue

Prerequisites 

  • Node.js (>v6.0.0 for nodemailer module) 
  • Code Editor (For Ex. VS Code, Atom) 
  • An account in Sendinblue

Start by creating a free account in Sendinblue

A Sendinblue free account offers 300 mails/day. Its setup is easy and straightforward. 

An introduction to Nodemailer 

Nodemailer, an open source project started in 2010, is annpm module for Node.js applications to send emails. Today, nodemailer is a de facto to send an email in Node.js. 

Highlights of Nodemailer 

  • It is a single module with zero dependencies  
  • It supports HTML Content  
  • Allows you to easily add attachments to messages 
  • Supports SMTP as default transport method; other supported transport methods are SES, Sendmail, Stream. 
  • OAuth2 authentication

Getting Started 

For this tutorial, I am using Nodejs v12.16.1 and VS Code as the Code Editor. 

Create a new directory nodemailer-example.  

Open the terminal or cmd inside the directory and run  

$ npminit --yes 

It will initialize a new npm package. 

Install dependencies 

Following different npm packages, we are going to use in this project. 

  • nodemailer – To send the mail 
  • express – To create APIs 
  • cors – To resolve the cross originresource sharing 
  • body-parser – To extract the body from the API request 
  • dotenv – To access the environment variables 
$ npm install --save nodemailer express cors body-parser dotenv 

This command will install all the dependencies. Now, we can start the coding. 

Project Structure 

Open the nodemailer-example in the code editor and create the following folders and files in it; not to worry, I will be explaining all the files and commands involved.  

nodemailer-example 
  |- routes 
    |- mail-api.js 
  |- src 
    |- send-mail.js 
  |- template 
    |- mail.html 
  |- .env 
  |- index.js 

Sendinmail Setup 

  • Login to your Sendinmail account. 
  • From the top-left menu, select SMTP & API. 
  • Select the SMTP tab. 
  • Click on Create a new SMTP key. Copy the key at some safe place.  
  • You can deactivate the SMTP key anytime. 
  • Now, open the .env file and create 2 key-value pair. 
USER=YOUREMAILADDRESS 
PASS=xxxxxxx-xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx 
  • USERThe email address using which you created the sendinmail account. 
  • PASS:SMTP Key 

By using .env file we are not exposing the credentials to the web.  

Using environment variables in the project is an industrial standard.  

Source Code 

  • Open the send-mail.js in the editor. 
  • Copy and paste the below code in it.
"use strict"; 
require("dotenv").config(); 
constnodemailer = require("nodemailer"); 
/** 
 * sendEmail 
 * @param{Object}mailObj - Email information 
 * @param{String}from- Email address of the sender 
 * @param{Array}to- Array of recipients email address 
 * @param{String}subject - Subject of the email 
 * @param{String}text - Email body 
 */ 
constsendEmail = async (mailObj) => { 
const{ from, to, subject, text } = mailObj; 
try { 
// Create a transporter 
lettransporter = nodemailer.createTransport({ 
host:"smtp-relay.sendinblue.com", 
port:587, 
auth: { 
user:process.env.USER, 
pass:process.env.PASS, 
      }, 
    }); 
// send mail with defined transport object 
letinfo = awaittransporter.sendMail({ 
from:from, // sender address 
to:to, // list of receivers 
subject:subject, // subject line 
text:text, // plain text body 
    }); 
console.log(`Message sent: ${info.messageId}`); 
return`Message sent: ${info.messageId}`; 
  } catch (error) { 
console.error(error); 
thrownewError( 
`Something went wrong in the sendmail method. Error: ${error.message}` 
    ); 
  } 
}; 
module.exports = sendEmail; 

Code Walk Through 

In the beginning, we are importing dotenv to get the environment variables from the .env file and nodemailer to send the email. 

The sendEmailfunction accepts an object. This object has from, to, subject, text fields. 

Please note that, from and USER must be same. 

The nodemailer.createTransportreturns a mail object. The transporter variable is storing the mail object. 

 let transporter = nodemailer.createTransport({
      host: "smtp-relay.sendinblue.com",
      port: 587,
      auth: {
        user: process.env.USER,
        pass: process.env.PASS,
      },
    });

Open SMTP tab in your sendinmail account and cross check the host and port.

In the auth object, we are passing the user and password from the environment variable.

Send the mail using sendMail method.

// send mail with defined transport object
    let info = await transporter.sendMail({
      from: from, // sender address
      to: to, // list of receivers
      subject: subject, // Subject line
      text: text, // plain text body
    });

It returns a Promise of Send Message Info. 

In the end, it is returning the message id.  

Express Route 

The sendEmail method is ready.  

Let’s create an express route for it. This is the API endpoint using which we can access the sendEmail function. 

Open the mail-api.js in the code editor and paste the below code. 

constexpress = require("express"); 
constrouter = express.Router(); 
constsendMailMethod = require("../src/send-mail"); 
// Post request to send an email 
router.post("/sendmail", async (req, res) => { 
try { 
constresult = awaitsendMailMethod(req.body); 
// send the response 
res.json({ 
status:true, 
payload:result 
        }); 
    } catch (error) { 
console.error(error.message); 
res.json({ 
status:false, 
payload:"Something went wrong in Sendmail Route." 
        }) 
    } 
}) 
module.exports = router; 

The express framework provides a Router method to create different HTTP methods. Here, we have created a POST method to send the mail.  

Instead of extracting the req.body parameters, we passed it as it is. The benefit of this approach is that if there is a change in argument or position, then we would not have to change it in all the places.  

In the end, we are exporting the router. Now, this can be used in the server side. 

Express Server 

Now, it’s time to create a server and expose the routes on it. 

Open the index.js and paste the below code in it. 

"use strict"; 
constexpress = require("express"); 
constbodyParser = require("body-parser"); 
constcors = require("cors"); 
constapp = express(); 
constmailAPI = require("./routes/mail-api.js"); 
// Express body parser 
app.use(cors()); 
app.use(bodyParser.json()); 
app.use( 
bodyParser.urlencoded({ 
limit:"50mb", 
extended:false, 
parameterLimit:50000 
  }) 
); 
// use the routes specified in route folder 
app.use("/api/v1", mailAPI); 
constport = process.env.PORT || 4444; 
//listen to the server 
app.listen(port, function () { 
console.log(`listening to the port ${port} .....`); 
}); 

The route is available on /api/v1/sendmail. 

Run the server. 

$ node index.js 
listening to the port 4444 ..... 

Send an Email using API 

There are couple of methods to test the API. 

Using the Postmanor using the Curl command. 

Using Postman 

Install Postman on your machine if it is not installed. 

Create a POST request. 

  • URL: http://localhost:4444/api/v1/sendmail 
  • Content Type: JSON – Body tab > select JSON from dropdown 

Request Body 

{ 
"from": "hello@schadokar.dev", 
"to": ["shubham@schadokar.dev"], 
"subject": "Mail from Nodemailer", 
"text": "Sending an email using nodemailer package." 
} 

Hit Send. Make sure the server is running. 

Learn Nodemailer Module in Node.js

On Success, the response returns the message id. Now, check your mailbox. 

If you are unable to find the mail in your Inbox, check the promotional mail folder. 

Learn Nodemailer Module in Node.js

Using Curl Command

Open the terminal or cmd.

In the below curl command, change the parameters and enter.

curl -X POST http://localhost:4444/api/v1/sendmail -H "Content-Type:application/json" -d '{"from": "hello@schadokar.dev","to": ["shubham@schadokar.dev"],"subject": "Mail from Nodemailer", "text": "Sending an email using nodemailer package."}'

Learn Nodemailer Module in Node.js

In this example, we have sent a simple text message to the recipient.  

Nodemailer also gives you an option to send the message in HTML format. 

Mail template 

Open the mail.html in the code editor and paste the below code. 

<div style="text-align: center;"">
 <h1 style="color: #3584c8;">Nodemailer Example</h1>
  <p>

   This is an example html template to demonstrate the sending email using html.   

<br />
Profile

Shubham Chadokar

Author

I am a Software Engineer who loves to write articles and tutorials on the latest technologies. I write majorly on Nodejs and Golang.