Send Emails in Node.js with Nodemailer

714
SHARES
3.2k
VIEWS

Introduction:

In this tutorial, we will learn how to send emails in Node with Nodemailer. As we know, sending emails in any website or application is an important functionality. First, we will setup node.js application using NPM commands. Then we will implement email functionality. We will use “nodemailer” package for our email system.

Requirements:

Setting up the project:

// create a project directory
$ mkdir send-email-node
$ cd send-email-node
// initialize NPM
$ npm init
// create a file called app.js
$ touch app.js

Install the following NPM:

  • Express is a Node.js framework. It’s the most popular framework as of now (the most starred on NPM).
  • Nodemailer is a module for Node.js applications to allow easy as cake email sending.
  • EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.
  • Body-Parser is node.js body parsing middleware.
$ npm i --save nodemailer express ejs body-parser

Require all packages in app.js

const express = require('express'),
      app = express(),
      nodeMailer = require('nodemailer'),
      bodyParser = require('body-parser'),
      port = process.env.PORT || 3000;

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.listen(port, () => {
   console.log('Server is listening on PORT: ' + port);
});

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

$ node app.js

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

$ mkdir views
$ cd views
$ touch index.ejs

We will use Bootstrap as the style framework and add the CDN link directly in the Index.ejs.

<!DOCTYPE html>
<html>
  <head>
    <title>Send Email with Nodemailer</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        Sending Email in Node.js with Nodemailer
      </div>
    </div>
  </body>
</html>

In app.js also create one route for home page

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

Now, started the server yet, initiate the server by the following command.

$ node app.js

It will start at http://localhost:3000

Creating a bootstrap form

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

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Send Email with Nodemailer</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <div class="container"><br>
      <h1>Send The Email with Nodemailer</h1><br>
      <form action="/send-email" method="POST">
        <div class="row">
          <div class="form-group col-md-4">
            <label for="to">To:</label>
            <input type="email" class="form-control" name="to">
          </div>
        
          <div class="form-group col-md-4">
            <label for="subject">Subject:</label>
            <input type="text" class="form-control" name="subject">
          </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 class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Send</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

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

const express = require('express'),
      app = express(),
      nodeMailer = require('nodemailer'),
      bodyParser = require('body-parser');
      port = process.env.PORT || 3000;
 
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.get('/', (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: 'your-email-here',
           pass: 'your-password-here'
      }
   });

   let mailOptions = {
      from: '"Meen" <sender-email-here>',
      to: req.body.to, // receiver Email
      subject: req.body.subject, // Subject line
      body: req.body.body, // plain text body
      html: '<b>Nodemailer is Working</b>' // html body
   };

   transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
          return console.log(error);
      }
      console.log("Message send Successfully");
      res.render('index');
   });
 });
app.listen(port, () => {
   console.log('Server is listening on 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 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. 

Muhammad Mubeen

Muhammad Mubeen

Mubeen is a full-stack web & mobile app developer who is very proficient in MEAN.js, Vue, Python, Ionic 4, Flutter, Firebase, ROR, and PHP. He has created multiple mobile and web applications. He is very passionate about sharing his knowledge.

Comments 1

  1. Selina says:

    Hello, thank you for posting this. When I inputted the code you have listed in the last step “Next step is to create a route for the post request sent by form and handle its data. So, our final app.js file will look like this.” into my app.js file I have over 15 errors. With me being an entry level programmer I am finding very little solutions to the errors. Can you comment why I am getting so many errors once I implemented your code? If not your instructions will unfortunately not work for me. I have node.js and Express downloaded on my computer and I’m using VS Code. I also already have coding implemented on my contact.html page for the form.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending