How to send mail using Node.js

In this post i  will show you how to send­ emails using G-Mail SMTP in Express(framework) Node.js.Sending a email using express js is pretty easy in node.js there are many library available for sending a mail.

Send mail using node.js express

Step 1: We are using express-mail libary for sending a mails and pugjs is a template engine which we are using for this post.

Step 2: Create a package.json file in your folder.

  "name": "send email using node.js",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: something going wrong\" && exit 1"
  "keywords": [
  "author": "wantcode",
  "dependencies": {
    "express": "^4.14.0",
    "pug": "^2.0.0-beta6",
    "express-mailer": "^0.3.1"

or you can directly genreate package.json using following commands.

npm init //initialize the npm 
npm install --save pug express express-mailer // install express mailer and pug dependencies

Step 3: Now come to main file called server.js.

// call the packages we need
const express = require('express');  // call express
const mailer = require('express-mailer'); // call express
const app = express(); // create a server
const port = process.env.PORT || 8000;  // set our port
// set the view folder to views
app.set('views', __dirname + '/template');
// set the view engine to pug
app.set('view engine', 'pug');
// Configure express-mail and setup default mail data.
mailer.extend(app, {
  from: '',
  host: '', // hostname
  secureConnection: true, // use SSL
  port: 465, // port for secure SMTP
  transportMethod: 'SMTP', // default is SMTP. Accepts anything that nodemailer accepts
  auth: {
  user: '', // gmail id
  pass: 'yourGmailPassword' // gmail password
// test route to trigger emails
app.get('/', function (req, res) {
  // Setup email data.
  var mailOptions = {
    to: '',
    subject: 'Email from SMTP sever',
    user: {  // data to view template, you can access as -
      name: 'Sonu Jangra',
      message: 'Hello welcome to my website wantcode'
  // Send email.
  app.mailer.send('email', mailOptions, function (err, message) {
    if (err) {
      res.send('There was an error sending the email');
    return res.send('Email has been sent!');
app.listen(port, function () {
  console.log("Example app listening on port ${port}!");

Step 4: Create a view called template/email.pug.

doctype html
    b Hi #{}
    p #{user.message}

Step 5: Run the app using node app.js

Check the action on browser using  : http://localhost:8000/


Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...