Node.Js Send Email Using Nodemailer

Today I’ll show you how to send email in Nodej.s using Nodemailer. Nodemailer is a module for Node.js to send emails. Let’s follow these steps:

Table of Contents

  1. Create a Project
  2. Install Packages
  3. Configure package.json
  4. Add Resources
  5. Create a Server
  6. Run the Project

Step 1 : Create a Project

First create a directory and enter it. Then type the following command line:

npm init

Step 2 : Install Packages

We need nodemailer package for the sending mail. We are also using express web framework. So we need to download both. Install both by typing this command:

npm install --save nodemailer express

To get rid of every time restart the server, we will use one package called nodemon server. Type this command to install nodemon server:

npm install nodemon --save-dev

We will use EJS as a templating engine. Let’s install EJS by typing this:

npm install --save ejs

We need to install a package called body-parser. It’ll help us to get all fields data at the server side. Let’s install:

npm install body-parser --save

Step 3 : Configure package.json

Open package.json file and add "start": "nodemon server"the line in scripts array. Have a look at my final package.json file:

package.json
{
  "name": "email-sender",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon server"
  },
  "author": "Md. Obydullah",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.2",
    "ejs": "^2.5.7",
    "express": "^4.16.4",
    "nodemailer": "^4.7.0"
  },
  "devDependencies": {
    "nodemon": "^1.18.11"
  }
}

If we change a file in our project, then nodemon server will restart the server automatically.

Step 4 : Add Resources

We have installed the express framework. It supports MVC. Let’s create two folders called public and views in the root directory. You can store static files like CSS, JavaScript, Images in the public directory.

We will use bootstrap for our project. You can download and store the CSS file in the public folder. You can also call bootstrap CSS from remote.

Let’s create a view file. In views folder, make a file called “index.ejs” and paste this code:

index.ejs
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Nodemailer Email Test</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container"><br />
      <h2 class="text-center">Nodemailer Email Test</h2><br />
		<form action="/send" method="post">
			<div class="form-group">
				<label>To</label>
				<input type="email" class="form-control" name="to" placeholder="Enter email">
			</div>
			<div class="form-group">
				<label>Subject</label>
				<input type="text" class="form-control" name="subject">
			</div>
			<div class="form-group">
				<label>Message</label>
				<textarea cols="5" rows="5"class="form-control" name="message"></textarea>
			</div>
			<button type="submit" class="btn btn-primary">Send</button>
		</form>
    </div>
  </body>
</html>

Step 5 : Create a Server

We are about to finish. In the root directory and a file called server.js and paste this code:

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', function (req, res) {
	let transporter = nodeMailer.createTransport({
		host: 'smtp.mailtrap.io',
		port: 465,
		secure: false,
		auth: {
			user: 'SMTP_USER',
			pass: 'SMTP_PASS'
		}
	});
	let mailOptions = {
		from: '"MyNotePaper" <[email protected]>',
		to: req.body.to,
		subject: req.body.subject,
		html: req.body.message,
	};

  	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);
});

Look at the /send route. I’ve used smtp.mailtrap.io as a testing mail provider. You can enter your own provider. You can also use google SMTP.

Step 6 : Run the Project

We have completed all steps. Let’s run the project by typing this command line:

npm start

If everything is correct, then the server will run. Visit http://localhost:3000 to the email sending form like this:

Write an email and Send that. I’ve received the email in the inbox.

The project file structure is:

I hope this article will help you.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.