Posted by Arjun on Wednesday 12th September 2018

Send Email using SendGrid in Express.JS application

How to SendGrid

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 pretty easy with SendGrid using @sendgrid/mail npm package.

For sending HTML emails we are going to use template engine called pugjs, this project was formerly known as Jade.

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

or

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

server.js

// call the packages we need
const express = require('express');  // call express
const mailer = require('@sendgrid/mail'); 
const app = express(); // create a server

mailer.setApiKey('yourSendGridKey');

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) {
       sendEmail({
            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,
      mailOptionsObject.data
    );

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

views/welcome.pug

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