Email Notifications with Twilio SendGrid and Firebase Functions

Coworkers setting up email notifications with SendGrid and Firebase
January 19, 2023
Written by
Twilion
Twilion
Reviewed by
Twilion

In this article, we're sending an email notification to all the registered users of our demonstration knowledge base, Twiliog. This is the second step in our build process for the broader app. (You can read more here.)

Here, you'll learn how to build, deploy and connect Twilio APIs through Cloud Functions for Firebase using react-redux libraries.

Prerequisites

If you haven’t followed the build from the beginning and are interested in setting up notifications, you’ll need to set up a few accounts (and change a few settings) before we begin.

  • Set up a Firebase Account
  • Set up a Sendgrid Account
    • We use SendGrid to send emails notifying new authors that their 2FA account is verified and they're ready to publish articles on our Twiliog site.
  • Set up a Twilio account and buy a number.
  • Deploy Firebase functions
    • Google Cloud Functions is Google's serverless computing solution for creating event-driven applications. Cloud Functions serve as a connective layer allowing you to weave logic between Google Cloud Platform (GCP) services by listening for and responding to events.
    • Follow the instructions specified in the previous article.

Set up your dev environment

Clone the git repo or download it.

Navigate to the project folder and install the dependencies.

npm install

Start up the frontend with:

npm start

Set up Firebase

Next, we will install the Firebase CLI.

Note again that you’ll need to have Firebase Blaze pricing in order to complete this step.

Navigate to the ‘functions’ folder and install the dependencies:

npm install 

Install Firebase CLI in the functions folder:

npm install -g firebase-tools

If you are running into issues around the version of Node being used, this is a great resource that can help:

https://help.dreamhost.com/hc/en-us/articles/360029083351-Installing-a-custom-version-of-NVM-and-Node-js

Now, log into Firebase:

firebase login

Select the project you want to use:

firebase projects:list

Switch to your new project with:

firebase use <projectname> 

Update the Twilio config information

In twiliog > functions > src > .env, update the environment variables with your Twilio credentials:

TWILIO_ACCOUNT_SID=AC…
TWILIO_AUTH_TOKEN=...

Update the Firebase config information

In twiliog > src > config > fbConfig.js. Update the firebaseConfig settings with your own project info:

const firebaseConfig = {
 apiKey: "...",
 authDomain: "...",
 projectId: "...",
 storageBucket: "...",
 messagingSenderId: "...",
 appId: "...",
 measurementId: "..."
};

Deploy the functions

Navigate back to your project folder from the functions folder.

cd ..

To deploy the functions to Firebase functions:

npm run functions:deploy

If there are any errors, you can display Firebase logs with:

firebase functions:log

Firebase Rules

Next, you’ll need to set your Firebase rules. You can use the following settings:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
          match /blogs/{blog}{
      allow read, write: if request.auth.uid != null
      }
      match /users/{userId}{
        allow create
        allow read: if request.auth.uid != null
        allow write: if request.auth.uid == userId
      }
  }
}

SendGrid setup

Now, we’ll move on to our SendGrid setup, which is how we’ll be sending the notifications. You can also see our Node.js Quickstart here.

Start by npm installing the sendgrid package:

cd functions
npm install --save @sendgrid/mail

Create a config.js file under function with:

require("dotenv").config();

module.exports = {
  SENDGRID_API_KEY: process.env.SENDGRID_API_KEY,
};

Create an .env file under functions with the SendGrid API key:

SENDGRID_API_KEY=SG.xyz

Finally, install dotenv:

cd functions
npm install dotenv

Next, we’ll move into the SendGrid console.

Steps in the SendGrid console

Create an API key under the API Keys section of the SendGrid console. Create a new API Key with Full Access.

Full access API Key for SendGrid

Next, create an email template for your notifications through the design library:

In the Design Library, create an email notification template

Once you’re happy with the mail, publish it and save the resulting template ID. We will be using it in a few steps.

Dynamic templates in SendGrid

Steps in the Firebase console

Deploy the function using the following code snippet:

npm run functions:deploy

Let that command complete, then check if the Function is deployed in your GCP console. In your Functions Dashboard, you should see a list of your deployed functions.

Check the Functions Dashboard for deployed functions on Google

Architecture diagrams

Here’s the architecture of the feature that we built using this methodology.

Architecture diagram email notifications to new authors

Code Explanation

Twiliog is built using the react-redux programming methodology.

We have a store to keep track of users, we dispatch actions to create entries in the Firebase store, and finally, upon creation of the user, we run a Firestore Function to send out an email to the new author upon account creation.

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp(functions.config().firebase);
const sgMail = require("@sendgrid/mail");
const config = require("../../config");
sgMail.setApiKey(config.SENDGRID_API_KEY);
export const sendEmail = functions.auth.user().onCreate((user) =>{
 return admin.firestore().collection("users").doc(user.uid).get().then((doc)=>{
   const userInfo =doc.data();
   const {email} = userInfo;
   console.log(email);
   const msg ={
     to: email,
     from: "yitpoojas@gmail.com",
     templateId: "d-2dc97740d02b42fda252048dd1547dab",
   };
   sgMail
       .send(msg)
       .then((response) => {
         console.log(response[0].statusCode);
         console.log(response[0].headers);
       })
       .catch((error) => {
         console.error(error);
       });
 });
});

We recommend storing the SG keys in the .env files. The keys start with SG. These keys are accessed through the config file as shown below:

require("dotenv").config();

module.exports = {
 SENDGRID_API_KEY: process.env.SENDGRID_API_KEY,
 TWILIO_ACCOUNT_SID: process.env.TWILIO_ACCOUNT_SID,
 TWILIO_AUTH_TOKEN: process.env.TWILIO_AUTH_TOKEN,
};

Which, in order, accesses the Sendgrid API key, Twilio Account SID, and Auth Token.

The following code is called whenever there is a new entry in the Firestore user collection. From the collection we grab the to email address and send the mail from the id yitpoojas@gmail.com. The body of the email is created through the dynamic templates that are available in the SendGrid portal. We just attach the template id – which we copied in an above step – in our code below:

export const sendEmail = functions.auth.user().onCreate((user) =>{
 return admin.firestore().collection("users").doc(user.uid).get().then((doc)=>{
   const userInfo =doc.data();
   const {email} = userInfo;
   console.log(email);
   const msg ={
     to: email,
     from: "yitpoojas@gmail.com",
     templateId: "d-2dc97740d02b42fda252048dd1547dab",
   };
   sgMail
       .send(msg)
       .then((response) => {
         console.log(response[0].statusCode);
         console.log(response[0].headers);
       })
       .catch((error) => {
         console.error(error);
       });
 });

And there you have it – you now have a notification email sent out when a blog author registers.

Here is the link to the GitHub repo, a work-in-progress website to include more Twilio modules.

Conclusion:

Through this article, you learned how straightforward it is to connect Firebase with SendGrid APIs and send out email notifications to new blog authors with just a few lines of code. Read more about the full Twiliog project, here.

About Authors

Pooja Srinath is a Principal Solutions Engineer at Twilio. She's focused on learning new software technologies that help create solutions, address use cases, and build apps to solve some of the industry's most challenging requirements. Pooja uses Twilio's powerful communication tools & APIs to build these ideas. She can be found at psrinath [at] twilio.com.

Yi Tang is a Senior Solutions Engineer at Twilio. She loves helping Twilio's customers achieve their business goals and is always looking for ways to improve and optimize their use of Twilio products. She can be found at ytang [at] twilio.com