Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

Send Email using SendGrid in Express.JS application

In this arti­cle, I will demon­strate a sim­ple exam­ple of send­ing emails using SendGrid in Express/ Node.js. Fortunately sending emails in express/node js is pretty easy with SendGrid using @sendgrid/mail npm package.

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": "arjunphp.com",
  "license": "ISC",
  "dependencies": {
    "express": "^4.14.0",
     "pug": "^2.0.3",
    "@sendgrid/mail": "^6.3.1",


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


// call the packages we need
const express = require('express');  // call express
const mailer = require('@sendgrid/mail'); 
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');

app.get('/', function (req, res) {
            toAddress: '[email protected]',
            subject: 'Email from SMTP sever',
            data: {  // data to view template, you can access as - user.name
               name: 'Arjun PHP',
               message: 'Welcome to arjunphp.com'
            htmlPath: "welcome.pug"
        }).then(() => {
          return res.send('Email has been sent!');
        }).catch((error) => {
          return res.send('There was an error sending the email');

const sendEmail = function(mailOptionsObject) {
    const html = pug.renderFile(
      __dirname + "/../views/email/" + mailOptionsObject.htmlPath,

    const msg = {
      to: mailOptionsObject.toAddress,
      from: config.get('emailFrom'),
      subject: mailOptionsObject.subject,
      html: html

    const status = sgMail.send(msg)
    return status;

app.listen(port, function () {
  console.log(`Example app listening on port ${port}!`);


doctype html
    b Hi #{user.name}
    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.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments