How to Send Email in Nodejs with Expressjs

Sunday, July 26, 2020 • 6 minutes to read


This is the 2nd part of the How to send email in Nodejs series. In the last section, we created the function to send the email using node cli.

In this section, we will use the Expressjs and expose the functionality as an API. To test the api, we're going to use 2 options Curl command and Postman.



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

Check out this step by step tutorial to Create an account in sendinblue.

Getting Started

Let's first install all the dependencies.

  • express - To create routes
  • body-parser - To access the parameters passed with API request
  • cors - To handle the cross origin resource sharing
  • dotenv - To access the .env file which we are going to use to save the credentials

Open the terminal inside the project and run the below command.

1npm install --save express body-parser cors dotenv

Project Directory Structure

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


In the last section, we entered the email and SMTP_KEY in the code, which is not recommended.
We should always use the environment variables in the code, to keep the secrets safe. Create a new file .env and paste your email and SMTP_KEY.



In the src folder, create a new file send-mail.js and paste the below code.

 1"use strict";
 3const nodemailer = require("nodemailer");
 4const path = require("path");
 6 * sendEmail
 7 * @param {Object} mailObj - Email information
 8 * @param {String} from - Email address of the sender
 9 * @param {Array} to - Array of receipents email address
10 * @param {String} subject - Subject of the email
11 * @param {String} text - Email body
12 */
13const sendEmail = async (mailObj) => {
14  const { from, to, subject, text } = mailObj;
16  try {
17    // Create a transporter
18    let transporter = nodemailer.createTransport({
19      host: "",
20      port: 587,
21      auth: {
22        user: process.env.USER,
23        pass: process.env.PASS,
24      },
25    });
27    // send mail with defined transport object
28    let info = await transporter.sendMail({
29      from: from, // sender address
30      to: to, // list of receivers
31      subject: subject, // Subject line
32      text: text, // plain text body
33      html: {
34        path: path.resolve(__dirname, "../template/mail.html"),
35      }, // html body
36    });
38    console.log(`Message sent: ${info.messageId}`);
39    return `Message sent: ${info.messageId}`;
40  } catch (error) {
41    console.error(error);
42    throw new Error(
43      `Something went wrong in the sendmail method. Error: ${error.message}`
44    );
45  }
48module.exports = sendEmail;

Let's understand the code

  • require("dotenv").config(); is used to load the .env file, so that using process.env.{KEY} we can access the environment variables defined in the .env file.
  • The function takes an object with to, from, subject and text arguments.
  • nodemailer.createTransport creating a transport object with all the required details of the message service provider and user access to that.
  • transporter.sendMail: Enter all the details to mail. The text field send a plain text while the html field send the mail in the html format.


Open the routes folder and create a new file mail-api.js. In this file, we will create a send email route.
This endpoint then triggers the sendEmail function, defined in the src directory.

Copy and paste the below code in the file.

 1const express = require("express");
 2const router = express.Router();
 3const sendMailMethod = require("../src/send-mail");
 5// Post request to send an email"/sendmail", async (req, res) => {
 7  try {
 8    const result = await sendMailMethod(req.body);
10    // send the response
11    res.json({
12      status: true,
13      payload: result,
14    });
15  } catch (error) {
16    console.error(error.message);
17    res.json({
18      status: false,
19      payload: "Something went wrong in Sendmail Route.",
20    });
21  }
24module.exports = router;

Instead of taking out the variables from the req.body, we directly send this to the function as it is accepting an object.
This approach is optional, if the application requires the input validation, then validate it at route end, instead of at method end. As it is for education purpose not for production.


In the html field of sendMail method, it can read the pure html code. But this is not recommended.
Instead you can create a mail.html template and give its path to it.
Create a new file mail.html and paste the below code in it.

1<div style="text-align: center;">
2  <h1 style="color: #3584c8;">Nodemailer Example</h1>
3  <p>
4    This is an example html template to demonstrate the sending email using
5    html.
6    <br />
7    🤗 🤗 🤗 🤗 🤗 🤗
8  </p>

You can use a dynamic html template, in which you pass the arguments. But that is out of the scope for this tutorial.


Open the index.js and paste the below code. This index.js is the entry point for this application. It is importing all the application route and creating a express server to host the application on 4444 port.

 1"use strict";
 2const express = require("express");
 3const bodyParser = require("body-parser");
 4const cors = require("cors");
 5const app = express();
 6const mailAPI = require("./routes/mail-api.js");
 8// Express body parser
12  bodyParser.urlencoded({
13    limit: "50mb",
14    extended: false,
15    parameterLimit: 50000
16  })
19// use the routes specified in route folder
20app.use("/api/v1", mailAPI);
22const port = process.env.PORT || 4444;
24//listen to the server
25app.listen(port, function () {
26  console.log(`listening to the port ${port} .....`);

Run Time

Now, the fun part. Let's send some emails.
Open the terminal inside the project directory and run the below command.

node index.js

This will start the server at 4444 if no PORT environment variable defined.

Open the Postman and create a POST request to localhost:4444/api/v1/sendmail.
In the Body tab, select the JSON option. Modify the body accordingly.

2    "from": "",
3    "to": [
4        ""
5    ],
6    "subject": "Mail from Nodemailer",
7    "message": "Sending an email using nodemailer package."

Hit Send.


Check Email

Open you email and check the inbox. If you could not find it in inbox try to check in promotion.

Text email

If you haven't used the html field in the sendMail then your mail will look like this.


HTML email

When you are using html field then it ignores the text field and only send the html message.



We have finished the api part of this application and with this our backend is completed.
Now, you can use any frontend framework to utilize this API.

You can find the complete code on the GitHub.
Thanks for reading.

Cover is designed in Canva


PreviousSecure Your Api Using Jwt in Golang

NextHow to Send Email in Nodejs