Monitoring Email Delivery/Open Rates in .NET Using Twilio SendGrid Webhooks

January 14, 2025
Written by
Eman Hassan
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

Monitoring Email Delivery/Open Rates in .NET Using Twilio SendGrid Webhooks

Introduction

Communication through emails is a priority for almost every business. The ability to send outgoing emails is important. But it is equally important to be able to measure the metrics around those emails. What is the number of users who actually opened the email? Was the email even delivered successfully or not? In this tutorial, you’ll learn how to monitor email delivery and open rates for a .NET application using Twilio SendGrid Webhooks.

Prerequisites

Building the app

First, log in to your SendGrid Account. You’ll need to create a new SendGrid API Key. For this tutorial, you can choose restricted access when you create your key. On the Restricted Access tab, be sure your API Key is set to allow Email Sending access.

Make sure to keep your API key somewhere safe to be able to use it later in the application.

Create a New .NET Web API Project

Open the terminal in VS Code and use the following command to create a new ASP.NET Core Web API project:

mkdir EmailMonitoring
cd EmailMonitoring
dotnet new webapi

Install SendGrid NuGet Package

In your terminal window in VS Code, run the following command to install SendGrid’s package.

dotnet add package SendGrid

Configure SendGrid in Your Application

Open the file appsettings.json and add the API Key you created for SendGrid. Replace the placeholder below with your API key that you copied earlier.

"SendGrid": {
    "ApiKey": "YOUR_SENDGRID_API_KEY"
  },

Implement Email Sending Functionality

Create a new file called SendGridSettings.cs. Add the following code.

public class SendGridSettings
{
    public string ApiKey { get; set; }
}

Now, load the added configuration to Program.cs. Under the first line of code that contains the builder’s definition, add this code:

// Load SendGrid settings
builder.Services.Configure<SendGridSettings>(
    builder.Configuration.GetSection("SendGrid"));

Set Up the Webhook Endpoint

In order to receive event notifications from SendGrid, you need to set up an endpoint that will be triggered with the SendGrid event webhooks. Create a new folder called Controllers. Then create a new file called WebhookController.cs. Add the following code to implement the endpoint and capture the event data from SendGrid. It will then write it in a log file called webhook_events.log.

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
[ApiController]
[Route("api/webhook")]
public class WebhookController : ControllerBase
{
   private readonly string _logFilePath = "webhook_events.log";
    [HttpPost]
    public IActionResult ReceiveEvent([FromBody] object payload)
    {
        var events = JsonConvert.DeserializeObject<List<SendGridEvent>>(payload.ToString());
        // Write events to a log file
        using (var writer = new StreamWriter(_logFilePath, append: true))
        {
            foreach (var sgEvent in events)
            {
                writer.WriteLine($"{DateTime.UtcNow}: Event: {sgEvent.EventType}, Email: {sgEvent.Email}, Timestamp: {sgEvent.Timestamp}");
            }
        }
        return Ok();
    }
}
public class SendGridEvent
{
    [JsonProperty("event")]
    public string EventType { get; set; }
    [JsonProperty("email")]
    public string Email { get; set; }
    [JsonProperty("timestamp")]
    public long Timestamp { get; set; }
}

In order to enable the controller’s mapping and the routing to the API, you need to edit the file Program.cs. Find the line var app = builder.Build(); and add following code:

builder.Services.AddControllers();
var app = builder.Build();
app.UseRouting();
app.MapControllers();

Run The App and Expose localhost With Ngrok

Run the app with the following command:

dotnet run

Then notice which localhost port is the one running the API. For example http://localhost:5255.

You will use Ngrok to generate a URL for you to expose your localhost port while testing the webhook API. Another alternative, if you don’t want to map to your localhost, is to deploy your API to a testing server then use the deployed endpoint’s URL for testing.

Remember to close the ngrok CLI after you’re done testing to close the opened ngrok’s tunnel.

If you have not already configured ngrok, set it up now. Do this by signing into ngrok and going to your setup dashboard. Here you will find the download and installation steps, and your account’s token, which you must use in your CLI. The setup dashboard will look like the image below:

Ngrok installation

Run the following command in ngrok CLI to generate your URL, replacing the placeholder with your port.

ngrok http http://localhost:<add-your-app-port-number>

It will return a URL that you can use for your localhost port that your app is running on as shown below:

ngrok generated URL

Copy the URL as you will need it with the route to the webhook endpoint in SendGrid.

Enable Event Webhooks

In order to be able to use webhooks in SendGrid, you need to enable the event webhooks manually in the settings by navigating to Settings > Mail Settings > Event Webhooks in the SendGrid dashboard.

Navigate to event webhooks

Click Create new webhook

Create new webhook

Add the details as shown below. Make sure the Post URL contains the ngrok url you exposed for your localhost, then add the route to the API to the end of this url: /api/webhook/. Also select the events: Opened and Delivered.

Event webhook settings

Testing your application

Now you will test your application's integration. Make sure your application is still running on the same port you created the ngrok link for.

Login to SendGrid’s dashboard. Go back to the event webhook you created and click the gear icon, then select Edit.

Edit event webhook

Then scroll down and click on Test Integration as shown below:

Test Integration

Then go back to the still-running ngrok CLI. You should see a trigger to the URL, and the status of the request as shown below:

Test run status

If you go back to your project’s folder, you should find a log file created called webhook_events.log. It contains the log of the triggered events that SendGrid sends in the test.

Event logs
Note that SendGrid sends all events. Since you chose the events for opened and delivered only, you will only receive these events with the published webhook.

A recommended practice is to save these logs in an analytics database that would help you get good insights on your emails’ delivery and open rates over time.

Wrapping Up

Twilio SendGrid’s event webhooks are very powerful and can help you evaluate the success of your email campaigns and make informed decisions upon accurate results. The most important thing to remember is that you need to design your webhook endpoint correctly to make sure it accepts the event’s data format without errors and make sure it is enabled for the webhook to be able to send the request to.

Eman Hassan, a dedicated software engineer and a technical author, prioritizes innovation, cutting-edge technologies, leadership, and mentorship. She finds joy in both learning and sharing expertise with the community. Explore more courses, code labs and tutorials at https://app.pluralsight.com/profile/author/eman-m.