Share Unsubscribe Events with Subusers with SendGrid Event Webhooks and Twilio Functions

October 26, 2021
Written by
Reviewed by
Paul Kamp
Twilion

SendGrid Event Webhooks and Twilio Functions

SendGrid’s subusers are a great way to segment your email sending and API activity. Splitting your email activity into subusers allows you to get separate statistics for each type of email you send. But what if you want to share data across multiple subusers?

In this article, you’ll learn how to use SendGrid’s Event Webhook and build a Twilio Function Service to share global unsubscribe data with multiple subusers.

Background

The world of email contains an incredible amount of data. At Twilio SendGrid, we provide you with industry-leading insights about how your emails are processed and engaged in real-time through Event Webhooks.

To recap, here’s The Nine Types of Email Events that you can receive with SendGrid’s Event Webhook. The world is your oyster for what you leverage these events for: storing in a datastore, responding to a bounced email, or building a custom analytics dashboard.

However, Event Webhooks require you to stand up a web server to receive events, which can be tricky. Wouldn’t it be awesome if you could utilize those events without the hassle?

Introducing Twilio Functions

Twilio Functions flow chart overview

Twilio Functions is a serverless environment that empowers you to write code to receive Events from Event Webhook without having to worry about maintaining or scaling web infrastructure - it's all managed seamlessly by Twilio.

Read on to see Twilio Functions + SendGrid Event Webhooks in action!

Prerequisites

To get started with this tutorial, you’ll need the following:

  • A free Twilio account (sign up with this link and get $10 in free credit when you upgrade your account)
  • A SendGrid account (you can get a Free account by signing up here)

You’ll need a Pro or Premier API plan or an Advanced Marketing Campaigns Plan if you want to test out subusers. To learn more about paid accounts, read more here.

​​In order to use SendGrid in a Twilio Function, you need to perform these four steps:

  • Create the Twilio Function Service where you’ll add the code to handle unsubscribe events.
  • Create a SendGrid API Key and add it as an environment variable in your Function Service.
  • Add the axios npm package as a dependency in your Function Service.
  • Configure SendGrid’s Event Webhook to POST events to your Twilio Function Service.

Read on to follow these steps in detail.

Create your Function Service

Function services are containers for your serverless environments, containing assets, functions, and environment details.

Navigate to the Functions section of the Twilio Console. Click the blue Create Service button and provide a name for your service such as SendGrid-Webhook-Service.

Name a Functions service

Then click Next.

This will open the editor for your new service. Within the service, we’ll create a function to receive and handle the actual Event Webhook HTTP requests from SendGrid.

Create Function

Click the blue Add + button and then select Add Function to create a new function. In the input field, change the path name to /webhook-handler. Set the visibility status to “Public” in the pulldown menu next to the title so that you can receive HTTP requests from SendGrid.

Open the /webhook-handler function in the functions editor and replace it with this code:

const axios = require('axios');

exports.handler = function (context, event, callback) {

  const instance = axios.create({
    baseURL: 'https://api.sendgrid.com/v3',
    timeout: 5000,
    headers: { 'Authorization': 'Bearer ' + context.API_KEY },
  });

  // Only handle unsubscribe events
  for (i in event) {
    if (event[i].event == 'unsubscribe') {
      console.log(event[i]);

      instance.get('/subusers').then((response) => {
        const subusers = response.data;

        promises = [];

        // Push this unsubscribe email to every other subuser
        for (s of subusers) {
          console.log(s.username + " " + event[i].email);

          promises.push(axios.post(
            'https://api.sendgrid.com/v3/asm/suppressions/global',
            { 'recipient_emails': [event[i].email] },
            {
              headers: {
                'Authorization': 'Bearer ' + context.API_KEY,
                'on-behalf-of': s.username
              }
            }
          ));

        }

        Promise.all(promises).then((response) => {
          console.log(response.data);
          return callback(null, response);
        }).catch((error) => {
          console.log(error);
          console.log(error.response.data);
          return callback(error);
        });

      })
        .catch((error) => {
          console.log(error);
          console.log(error.response.data);
          return callback(error);
        });

    }
  }

};

This code accepts HTTP requests from SendGrid’s Event Webhook, then extracts the email from an unsubscribe event and pushes the info to the rest of your SendGrid subuser.

Remember to click the Save button to save your changes.

Add SendGrid Credentials as an environment variable

You’ll require an API Key for Functions to work with SendGrid’s API.

To get your SendGrid API key:

  • Login to your SendGrid parent account and go to Settings > API Keys in the left menu
  • Click “Create API Key” in the top-right corner
  • Leave the selector on “Full Access”
  • Give the key a name like Twilio Function, and hit “Create & View”
  • Take note of this key that you will need later, as it won’t be displayed again

Create a SendGrid API Key

Next, navigate back to the Functions section of the Twilio Console and click on the name of the service you created.

Here, you will add your SendGrid API key as an environment variable. On the lower half of the page, look under the Settings heading and click Environment Variables.

Environment variable setting in Functions

To add the SendGrid’s API key to the Twilio Function environment, create the environment variable by typing API_KEY in the empty Key field, then paste the SendGrid API key you have saved into the empty Value field.

Add an environment variable in Functions

Click on the blue Add button to save changes.

Add Axios as a dependency

You will use Axios to make HTTP requests to SendGrid’s API. In the Functions editor in your Twilio Console, click Dependencies under Settings to open the dependencies editor.

In the empty MODULE input type axios and in the VERSION input to the right, type *. Then click the Add button. This will add the latest version of the axios package to your Function Service.

Add a dependency in Twilio Functions

Click Save beneath the editor. Finally, at the bottom of the screen, click the blue Deploy All button to deploy your function service. Your Twilio Function Service is now ready to listen for webhook events.

Connect your SendGrid Subusers to the service

Now, with the Twilio Function prepared, you will configure your SendGrid subusers’ Event Webhook to send events to your new Twilio Function.

Copy your Twilio Function Public URL

Click on the /webhook-handler function under the Functions heading to reveal the code editor.

Copy the Functions URL

Then click the blue Copy URL link to copy the url to connect to your Twilio Function.

Configure subusers to send Event Webhooks to your Twilio Function

With the Twilio Function url copied, you will use it to configure SendGrid’s Event Webhook to send events to Twilio Function.

Login to your SendGrid subuser accounts, go to Settings > Mail Settings.

Event Webhook settings inside SendGrid

Click the Event Webhook button to open your Event Webhook setting and paste the Twilio Function URL you have copied in the HTTP Post URL input. Next, ensure that the “Unsubscribed” input option under “Engagement Data” is selected.

Finally, click the blue SAVE button.

Save Event Webhook settings in SendGrid

Repeat this step for every subuser so that unsubscribe events seen at their accounts are sent to your Twilio Function.

Testing your Twilio Function

To test out your Twilio Function, with the Event Webhook screen open, click on the Test Your Integration button under Integration Testing to send sample events to the public URL of your Twilio Function.

Pro Tip: Enable Live Logs at Twilio Function to see real-time events coming into the Function Service!

Events streaming into a live Twilio Function

Voila! You’ve successfully created your first Twilio Function to share unsubscribe data using SendGrid’s Event Webhook!

As recipients interact with your email such as choosing to opt out of all emails using SendGrid’s Preference Center, this data will be sent to your Twilio Function and shared across subusers.

Opt out preferences dialog

Conclusion

If you have come this far, you’ve managed to set up a Functions service to accept HTTP requests from Event Webhooks, listen for unsubscribe events, then make HTTP requests to SendGrid’s API to share unsubscribe emails with your subusers.

I hope you had a great time building this and learned more about SendGrid’s Event Webhooks and Twilio Functions.

Next Steps

Start exploring other ways to harness the power of your email data! For example, identifying email opens triggered by Apple Machines with our Apple Machine Open Indicator event field.

While you’re at it, I also highly recommend that you check out our guide on 15 Ways You Can Use Data to Engage Your Customers at every step of their journey.

Bernard Chang is a solutions engineer at Twilio, specializing in Twilio’s cloud email solutions and email program strategy across the Asia-Pacific region. His aspirations are to bike around the world, and to help businesses send better and more reliable email through the world’s most widely-used cloud email platform. He can be reached at bchang [at] twilio.com or LinkedIn.