Nodejs Sending mails using sendgrid and email tracking.

Nodejs is a very Amazing server side programming language you can use to create a stunning web apps or website. it is said that node js is a very fast in performing request and response.
Because node is asynchronous and single-threaded so every Input/output operation does not wait for other operation to be completed for execution. In nodejs only one single process is run all time and this single process handle all input and output process. it does not create seperate process for each requests instread all input/output operations are executed in  separate threads, 
Development is still on to make node js more faster.

in this article we will learn how to send emails in node js using sendgrid also we will learn how to track an email has been read or not by a particular user. We will store a flag 1 in a database table as user opens the email. 

sendgrid module is availabe here https://www.npmjs.com/package/

you can install it by this command 

npm install @sendgrid/mail –save

is order to send emails using sendgrid you need an api key. to obtain an api key from sendgrid you could create an account here https://app.sendgrid.com/ . while sendgrid is a paid service but you can use it for free but in free acount you can send only limited emails per day.

Below is the shortest example to send email using send grid.

exports.send_mail = function(req, res) {

    const sgMail = require('@sendgrid/mail');
    var email_to = 'sam@gmail.com';
    var subject = 'sendgrid test email';
    var final_body = 'Hi sam , how are you';
    var final_html_body = 'Hi sam, how are you';

    sgMail.setApiKey('SG.

      const msg = {
      to: email_to,
      from: 'Sendgrid ',
      subject: subject,
      text: final_body,
      html: final_body,
    };

    sgMail.send(msg);
}

This is a simple example but in actual task we may have to use an html file as body of an email when we send emails like newsletters, signup confirmations or any other infomative emails to users. To read an html file in node js we have to use fs module. fs is a file system module that is used to read and write file in node js and other module we will use is async module. Async module is used to avoid callback hell. Nodejs is asyncronous and not straight forward as other programming language like php, In order to execute second function it does not wait for first function to be completed. Some operations like querying a database table or reading a file from file system requires a callback function and this callback function is executed when parent operation does complete its process. Return values of this operations can only be taken in callback function. 
In below code we are using async.waterfall method. all functions will be execute one by one in the order as they are written in the code. first function will be execute and when we call callback(null) function any where in the code of our first function then it will call next callback function and so on. You can see in the code how we are passing values from function to function.

exports.send_mail = function(req, res) {
 
    async.waterfall([
        function(callback) {
            fs = require('fs')
            fs.readFile('views/
              if (err) {
                return console.log(err);
              }
                email_template = template;

                callback(null,email_template) // data send to next function
            });
            
        },
        function(email_template, callback) {
            var email_to = email_row.to_email;
            var subject = email_row.subject;
            var body = email_row.body;
            
            //we can replace some string with our new string in template output

            var final_body = email_template.replace(/

            const msg = {
                to: email_to,
                from: 'WorkMob ',
                subject: subject,
                text: final_body,
                html: final_body,
            };
            sgMail.send(msg);
            
         },
    ])//end waterfall
}

Email Tracking.

After sending email to users if you want to know that email has been read or not then put below img tag any where in the email body. You can put user_id or any other unique id or as many parameters as you want in this url. This url should return an one pixel image as output.

This url should call below function. This function will perform two types of operations. first it should create a record database with user_id and read flag. second it should return an 1 pixel image.

exports.tracker = function(req, res) {
  var err = 0;
  var errors = {};

  var id = req.query.id;
  
  if(typeof id == “undefined” || id == “” || id == “0”) {
    err = 1;
  }
  
  if(err == 0) {
    var postdata = {};
    postdata[“id”] = id;
// database query to story recored in a table

    request.get({url: url, qs: postdata}, function(err, httpResponse, respBody) {
      var img = fs.readFileSync(‘public/image.jpg’);
      res.writeHead(200, {‘Content-Type’: ‘image/jpg’ });
      res.end(img, ‘binary’);

    });    
  }

}

You code in this function to insert a user_id, date and flag 1 for read in a database table.
This table can be used as a email tracking report.

Leave a Reply

Your email address will not be published. Required fields are marked *

twenty − six =