AppDividend
Latest Code Tutorials

How To Send Email In Node Tutorial

8

We can send emails in Node using the Nodemailer library. We will use an Express Framework on the top of the Node.js application. Email is one of the most used tools for communication in web applications because it helps you reach your users directly, build your brand, or send general notifications.

Prerequisites

To follow along, you will need to have Node.js and npm (Node Package Manager) installed locally.

How To Send Email In Node

There are many Node.js modules for sending e-mails. Amongst them, nodemailer is the most popular choice. It is a module that gives you the ability to easily send emails without hassle.

The Simple Mail Transfer Protocol (SMTP) is a protocol for sending e-mail messages between servers. Most e-mail systems that send mail over the Internet supports SMTP based sending.

And guess what? SMTP is the main transport used by nodemailer for delivering messages.

Step 1: Create a project and configure it.

Create a project directory and in that type the following command in it.

npm init

We are going to use a nodemailer package for sending the email. Also, we are using an express web framework, so let us download both of them.

npm install --save nodemailer express

To get rid of every time restart the server, we are using one package called nodemon server.

npm install nodemon --save-dev

In the root directory, create one js file called server.js

// server.js

var express = require('express'),
    path = require('path'),
    nodeMailer = require('nodemailer');

    var app = express();
    var port = 3000;
    app.listen(port, function(req, res){
      console.log('Server is running at port: ',port);
    });

This is just a boilerplate to start our project. One thing we need to do is that we need to modify start script in a package.json file.

// package.json

"scripts": {
    "start": "nodemon server"
  },

So, when we have to start the node server, we just need to write the following command. 

npm start

If we change the file, then it will restart the server automatically.

Step 2: Use EJS as a templating engine.

Now, we need to install a templating engine called ejs(embedded javascript) by typing the following command.

npm install --save ejs

Create one directory in the root folder called the public.

// server.js

app.set('view engine', 'ejs');
app.use(express.static('public'));

We are setting an ejs templating engine for our application. Also, we are serving static files from the public directory.

In the root folder, we also need to create one more folder called views. In that create one file called index.ejs.

// index.ejs

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Nodemailer Email Example</title>
    
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        Sending Email in Node.js
      </div>
    </div>
  </body>
</html>

We have used bootstrap CSS class here, so the first thing we need to do is include the library inside the public folder.

<link rel="stylesheet" href="bootstrap.min.css">

Also, create one route for the home page by typing the following code.

// server.js

app.get('/', function (req, res) {
   res.render('index');
});

Now, if you have not started the server yet, please initiate the server by the following command.

npm start

It will start at the port 3000. Switch to the URL: http://locahost:3000

send email in expressjs

Step 3: Create a basic bootstrap form.

Create one bootstrap form to send the email. We are going to put that form in the index.ejs file.

<!-- index.ejs -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Nodemailer Email Example</title>
    <link rel="stylesheet" href="bootstrap.min.css">
  </head>
  <body>
    <div class="container"><br />
      <h1>Send The Email</h1><br />
      <form action="/send-email" method="post">
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="to">To:</label>
            <input type="email" class="form-control" name="to">
          </div>
        </div>

        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="subject">Subject:</label>
            <input type="text" class="form-control" name="subject">
          </div>
        </div>

        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="body">Body:</label>
              <textarea cols="5" rows="5"class="form-control" name="body"></textarea>
            </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Send</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

send email using nodemailerOur primary form will look like this.
Now, set the post action of the form.

<!-- index.rjs -->

<form action="/send-email" method="post">

However, to get all the fields data on the server side, we need to install one package called the body-parser package.

Step 4: Write the code that sends the email.

npm install body-parser --save

Use this package in our express framework by the following code.

// server.js

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

Next step is to create a route for the post request sent by form and handle its data. So, our final server.js file will look like this.

// server.js
var express = require('express'),
    path = require('path'),
    nodeMailer = require('nodemailer'),
    bodyParser = require('body-parser');

    var app = express();
    app.set('view engine', 'ejs');
    app.use(express.static('public'));
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    var port = 3000;
    app.get('/', function (req, res) {
      res.render('index');
    });
    app.post('/send-email', function (req, res) {
      let transporter = nodeMailer.createTransport({
          host: 'smtp.gmail.com',
          port: 465,
          secure: true,
          auth: {
              user: 'xxx@xx.com',
              pass: 'xxxx'
          }
      });
      let mailOptions = {
          from: '"Krunal Lathiya" <xx@gmail.com>', // sender address
          to: req.body.to, // list of receivers
          subject: req.body.subject, // Subject line
          text: req.body.body, // plain text body
          html: '<b>NodeJS Email Tutorial</b>' // html body
      };

      transporter.sendMail(mailOptions, (error, info) => {
          if (error) {
              return console.log(error);
          }
          console.log('Message %s sent: %s', info.messageId, info.response);
              res.render('index');
          });
      });
          app.listen(port, function(){
            console.log('Server is running at port: ',port);
          });

Here, I have shown you to send the email via Gmail. You can use any other host. You just need to grab their API keys.

If you are using Gmail then please update your credentials in the options object.

If email is successfully sent then, our form page index.ejs will return otherwise check the console in the terminal. You will get an error over there. This is the example of Send email using a nodemailer.

Fork me on Github.

Github Steps To Follow: 

  1. Clone the repository.
  2. In the project type: npm install
  3. Go to the server.js and configure your email client.
  4. Start the server by the typing: npm start

If you have any doubt then ask in a comment below.

8 Comments
  1. Xander says

    Hello,

    I am trying to send files and images using nodemailer.
    I know I can do attachments: from nodemailer but I want to be able to upload something using and then being able to do req.body.something.

    People say I need to use multer for this and enctype=”multipart/formdate” in the tag.
    This first of all would upload it to my server and secondly I can’t seem to get that work either.

    I am already stuck on trying to get this to work for quite a while so I was wondering if you could make a tutorial on this or help me out when ever you have some spare time.
    I can also give you a copy of my code I am using at the moment and all the modules I have on there.

    I am sorry if I am asking to much from you but I am stuck for a while now and couldn’t find a good or clear answer for some beginning node.js developer.

    -A desperate person

  2. Wayne says

    Hi,

    Trying this but all I get in the console is { submit: ‘ ‘ }

    app.post(‘/send-email’, function (req, res) {
    console.log(req.body);
    });

    Any help would be awesome.

  3. jaay says

    @Krunal
    Hi, i have been searching the same using Angular 2.! Can you pls post tutorial on how to send mail using Angualr 2

  4. J4GD33P 51NGH says

    What if two step verification is enabled for sender email?

  5. Meer Hama says

    it works locally but it does not work when i deploy it

  6. Mudrak Patel says

    Hi Krunal, nice article. I am working on a MEAN stack project. I have a contact form that has 4 fields: to, from, subject and body. The contact form has a button that when clicked should send email to the email address written in the “to” field. Now I DONOT want to include my email password in any file in my entire project. Is there any way to do this?

    1. Amit says

      you can put it in the .env file and put .env file into the .gitignore file so that when you push your code,
      your credentials will not get posted.

  7. raju vais says

    hello,
    thanks for it
    if i am not using gmail service instead of that i am using info@motivesite.com
    so what will be host name and port
    please help me

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.