AppDividend
Latest Web Development Tutorials

How To Send Email In Node.js Tutorial

990

How To Send Email In Node.js Tutorial is today’s main topic. We will use an Express Framework on the top of the Node.js application. Sending the emails in our web application is always there no matter what type of web application you are building. Today, I will show you how to do this with an example. Send email in Node.js tutorial with an example.

Send Email In Node.js

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 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 templating engine called ejs(embedded javascript) by typing following command.

npm install --save ejs

Create one directory in the root folder called public.

// server.js

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

We are setting 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 library inside the public folder.

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

Also, create one route for home page by typing 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 nodemailer

Our 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 fields data at the server side, we need to install one package called 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 nodemailer.

Download Project 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.

Leave A Reply

Your email address will not be published.