Email module is a very important feature of any web or mobile application. Every web or mobile application needs email functionality within it to update users about the latest offers, discounts and any other type of communication.

These days, Web development using the node.js is on its peak and almost every company is using node.js to build their product. So in this tutorial, we are going to learn how to send email in node.js using Node Mailer.

For this tutorial, we are going to use Gmail as an email service provider. There are lots of other email hosting providers that you can use instead of Gmail.

Prerequisite

Setup Initial Project Structure

In this article, our main focus is to learn how to send email in node.js so you should know how to structure your node.js app to scale in the future.

So let’s start and move further to send email in node.js 🙂

Create package.json file

First, we are going to create a package.json file for our project and then install the required dependencies.

Run the below command that will create a package.json file in the root folder

npm init

Install dependencies

We are using the express.js framework along with other essentials dependencies like body-parser, pug etc. If you don’t know about these terms then you can learn from here.

npm install express body-parser pug --save

Create Node.js Server to send email

For sending email in our application, we need a node.js server which handles all the request operations of the project.

Final Code to send email in node.js

After installing dependencies, create a file server.js and paste below code into that file.

const express = require('express'),
    bodyParser = require('body-parser'),
    nodeMailer = require('nodemailer');

const server = express();

// add middleware to parse the json
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({
    extended: false
}));

// Set up routes
server.post('/send-email', async (req, res, next) => {
    try {

        let {
            email
        } = req.body;

        if (!email) {
            return res.status(400).send({
                "error": {
                    "message": " Email requied"
                }
            });
        }

        let transporter = nodeMailer.createTransport({
            host: 'smtp.gmail.com',
            port: 465,
            secure: true,
            auth: {
                user: 'xxxxxx@gmail.com',
                pass: 'xxxxxxx'
            }
        });
        let mailOptions = {
            from: '"CodesQuery" <xxxxxxx@gmail.com>',
            to: email,
            subject: 'Testing Email',
            html: '<b>Send email in Node.js | Tutorials by CodesQuery</b>'
        };

        transporter.sendMail(mailOptions, (error, data) => {
            if (error) {
                throw new error('Something went wrong')
            }
            console.log(data);
            return res.status(200).send({
                "status": true,
                "message": "Email Send Successfully."
            });
        });
        
    } catch (err) {
        console.log(err);
        return res.status(200).send({
            "error": {
                "message": "Something went wrong"
            }
        });
    }
});

server.get('*', (req, res, next) => {
    next();
});


// catch 404 error
server.use(function (req, res, next) {
    const err = new Error('Requested URL Not Found !');
    err.status = 404;
    next(err);
});

//Error handler
server.use(function (err, req, res, next) {
    res.locals.message = err.message;

    // render the error page
    res.status(err.status || 500);
    res.send({
        "error": {
            "message": res.locals.message
        }
    });
});

server.listen(5000, function () {
    console.log('Express server listening on - http://' + 'localhost' + ':' + 5000);
});

If you are not able to understand the code then do not worry. I will explain it in details. 🙂

Here, I am using just one file server.js to explain the things. If you are reading this article means you have sound knowledge on how to create a node.js server and how to use express.js for building a scalable REST API using node.js.

Understanding the code for sending email in node.js

Let’s breakdown the above code and then understand each line in detail.

  • From Line 1 to 5: In these lines, we just import the required dependency for the project.
const express = require('express'),
    bodyParser = require('body-parser'),
    nodeMailer = require('nodemailer');

const server = express();
  • From Line 8 to 11: Between these lines, we are parsing incoming request. To learn more about body-parser uses and benefits click here.
// add middleware to parse the json
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({
    extended: false
}));
  • From line 14 to 64: This is the core of this article. This code tells how to send email in the node.js application. Let’s move on other lines, We will understand about this function in details. wait a minute. 🙂
  • Line 66 to 68: In this line, we are handling all those requests from the client which URL is not present in our application.
server.get('*', (req, res, next) => {
    next();
});
  • Line 72 to 76: Here, we are handling all the URLs which is not present in the node.js application and sending an appropriate response to the client.
// catch 404 error
server.use(function (req, res, next) {
    const err = new Error('Requested URL Not Found !');
    err.status = 404;
    next(err);
});
  • 79 to 89: These lines are responsible for the global error handling in the application.
//Error handler
server.use(function (err, req, res, next) {
    res.locals.message = err.message;

    // render the error page
    res.status(err.status || 500);
    res.send({
        "error": {
            "message": res.locals.message
        }
    });
});
  • 91 to 93: These codes start our node.js application on port 3010 to serve the requests from the clients.
server.listen(5000, function () {
    console.log('Express server listening on - http://' + 'localhost' + ':' + 5000);
});

Now let’s go back to the line 14 to 64 and understand how the things are working to send email in node.js

We create an HTTP POST method to receive the email id at which we need to send the email and then get that from the req.body object and store it into const variable email.

We are using the nodemailer library for sending the email So let’s install that into the application by running the below command.

npm i --s nodemailer

After installing the npm library let’s move back to the code again and see the things.

From line 29 to 37, we are creating a transport for the nodemailer because it needs transport to send email. Here, we are using Gmail host.

let transporter = nodeMailer.createTransport({
            host: 'smtp.gmail.com',
            port: 465,
            secure: true,
            auth: {
                user: 'xxx@xx.com', //replace it with your gmail username
                pass: 'xxxx'        //replace it with your gmail password
            }
        });

After creating the transporter, we need to configure the options object for the nodemailer. Below is the basic object for sending email in node.js using nodemailer npm library.

let mailOptions = {
            from: '"CodesQuery" <your_gmail_id@gmail.com>',
            to: email, //sender email id
            subject: 'Testing Email', //subject
            html: '<b>Send email in Node.js | Tutorials by CodesQuery</b>' //email body
        };

If you are using Gmail then you need to allow request form less secure app from here.

Once less secure enabled then you can send email from your Gmail account using the below code.

transporter.sendMail(mailOptions, (error, data) => {
            if (error) {
                throw new error('Something went wrong')
            }
            console.log(data);
            return res.status(200).send({
                "status": true,
                "message": "Email Send Successfully."
            });
        });

If email sending is successful then we return a successful response to the client otherwise send an error response with a message.

Conclusion

In this tutorial, we learn how to send email in node.js using the nodemailer library and Gmail.

You can use any other third party services like Aweber, SendGrid, MailChimp, Convert kit instead of using Gmail. To use other email services rather than Gmail then you just need to replace the transporter setting with their settings.

Hope you like this tutorial, if you have any doubt or suggestion then comment in the comment box. 🙂

Codecademy Web Development
Pin It