How to setup Sendgrid in Node.js platform in simple way

Prerequisites

Be sure to perform the following prerequisites to complete this tutorial. You can skip ahead if you've already completed these tasks.

  1. Sign up for a SendGrid account.
  2. Enable Two-factor authentication.
  3. Create and store a SendGrid API Key with Mail Send > Full Access permissions.
  4. Complete Domain Authentication.
  5. Install Node.js.


Create and store a SendGrid API key

Unlike a username and password — credentials that allow access to your full account — an API key is authorized to perform a limited scope of actions. If your API key is compromised, you can also cycle it (delete and create another) without changing your other account credentials.

Visit our API Key documentation for instructions on creating an API key and storing an API key in an environment variable. To complete this tutorial, you can create a Restricted Access API key with Mail Send > Full Access permissions only, which will allow you to send email and schedule emails to be sent later. You can edit the permissions assigned to an API key later to work with additional services.

Once your API key is assigned to an environment variable — this quickstart uses SENDGRID_API_KEY — you can proceed to the next step.

export SENDGRID_API_KEY=<Your API Key>


Verify your Sender Identity

To ensure our customers maintain the best possible sender reputations and to uphold legitimate sending behavior, we require customers to verify their Sender Identities by completing Domain Authentication. A Sender Identity represents your 'From' email address—the address your recipients see as the sender of your emails.



Install the helper library

To install the Twilio SendGrid helper library, type the following command into the terminal.

npm install --save @sendgrid/mail


Create template in Sendgrid Application

https://app.sendgrid.com/


Create new file email.js to send emails

Use this file for sending email as I have added validation to avoid email fail

const sgMail = require('@sendgrid/mail')

function IsValidEmail(email: string) {
    var reEmail = /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/;


    if (!email.match(reEmail)) {


        return false;
    }


    return true;
}



const sendGridKey = "Your sendgrid secret key"
sgMail.setApiKey(sendGridKey)




function validateEmailList(emailList: any) {
    let newEmailList: any = [];
    emailList.forEach((email: any) => {
        if (IsValidEmail(email.email)) {
            newEmailList.push(email);
        }
    });
    return newEmailList;
}
function validateEmailString(email: string) {
    return IsValidEmail(email);
}
function generatePersonalizationObject(toList: Array<{ email: string }>, subject: string) {
    let personalizationArray: Array<{ to: Array<{ email: string }>, subject: string }> = [];
    toList.forEach(element => {
        let personalization = {
            to: [
                {
                    email: element.email
                }
            ],
            subject: subject
        }
        personalizationArray.push(personalization);
    });
    return personalizationArray;
}


/**
 * https://sendgrid.com/docs/for-developers/sending-email/personalizations/
 * to {array}  [{ "email": "recipient1@example.com" }]         
 * templateName {string} 'template-1'
 * replacebleData {object} {}
 */
export default {
    sendEmail: async (to: Array<{ email: string }>, subject: string, templateName: string, replacebleData: any) => {
        const from: string = functions.config().email.article_emails.from;
        new Promise<boolean>((resolve, reject) => {
            const isProd = functions.config().env.prod === "true" ? true : false;
         
            let filteredToList = validateEmailList(to);
            let isAllGoodFrom = validateEmailString(from);


            if ((!filteredToList.length) || !isAllGoodFrom) {
                console.log('Some data is missing in to, from');
                console.log('To List', filteredToList);
                console.log('form', from);
                reject(false);
            }


            const msg = {
                "personalizations": generatePersonalizationObject(filteredToList, subject),
                from: from,
                templateId: templateName,
                dynamicTemplateData: replacebleData,
                asm: {
                    'group_id': 'groupId', /* This is for unsubscription url*/
                    'groups_to_display': [15913] /* This is for unsubscription preference*/
                },
                subject: subject
            };
            console.log(JSON.stringify(msg));
            sgMail.send(msg).then((success) => {


                resolve(true)
            })


        })


    }

}


Call this file for sending emails


const replacebleData = {
        key:"Value"
    }
await email.sendEmail(emailArray, subjectLine, templateId, replacebleData);   

Published by Umashankar Pardhi

Comments

umashankar-pardhi-gajkuf

Umashankar Pardhi Feb 14, 2021, 5:32:15 PM

Very Good

umashankar-pardhi-gajkuf

Umashankar Pardhi Feb 14, 2021, 5:30:19 PM

This is good article

Reply heres...

Login / Sign up for adding comments.