Skip to content

Send Email using G-Mail SMTP in Express/Node.js

Last updated on November 21, 2022

In this arti­cle, I will demon­strate a sim­ple exam­ple of send­ing emails using G-Mail SMTP in Express/ Node.js. fortunately sending emails in express/node js pretty easy, in node.js there are many open-source email libraries are available.

In this tutorial, we are going to use express-mail library. For sending HTML emails we are going to use a template engine called pugjs, this project was formerly known as Jade.

Create a package.json file and keep it in any folder. Put the below code in it.

  "name": "sending-emails-with-express-mailer-gmail-smtp",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "keywords": [
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.14.0",
    "pug": "^2.0.0-beta6",
    "express-mailer": "^0.3.1"


issue npm init command to generate package.json and after generating, issue following commands to install express js, pugjs and express mailer dependencies, npm install --save pug express express-mailer


// 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 + '/views');
// set the view engine to pug
app.set('view engine', 'pug');

// Configure express-mail and setup default mail data.
mailer.extend(app, {
  from: '[email protected]',
  host: '', // hostname
  secureConnection: true, // use SSL
  port: 465, // port for secure SMTP
  transportMethod: 'SMTP', // default is SMTP. Accepts anything that nodemailer accepts
  auth: {
  user: '[email protected]', // gmail id
  pass: 'yourPassword' // gmail password

// test route to trigger emails
app.get('/', function (req, res) {
  // Setup email data.
  var mailOptions = {
    to: '[email protected]',
    subject: 'Email from SMTP sever',
    user: {  // data to view template, you can access as -
      name: 'Arjun PHP',
      message: 'Welcome to'

  // 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}!`);


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

Run the app with the following command:

$ node app.js

Then, load http://localhost:8000/ in a browser to see the output.

0 0 votes
Article Rating
Notify of

Most Voted
Newest Oldest
Inline Feedbacks
View all comments