Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

StrongGrid

> 编程语言
Open source

Strongly typed library for the entire SendGrid v3 API, including webhooks

197 stars0 likes2 views
WebsiteGitHub

About

Strongly typed library for the entire SendGrid v3 API, including webhooks

StrongGrid

Release Notes NuGet (stable) Feedz.IO (prerelease)

About

StrongGrid is a strongly typed library for SendGrid's v3 API.

It started out in February 2016 as a fork of SendGrid's own library. At the time, the SendGrid C# client for their API extensively used the dynamic type which was very inconvenient and made it very difficult for developers. Furthermore, their C# client only covered the mail end point but did not allow access to other end points in their email marketing API such as creating lists and segments, importing contacts, etc. I submited a pull request to SendGrid in March 2016 but it was not accepted and eventually closed in June 2016.

In October 2016 I decided to release this library as a nuget package since SendGrid's library was still using dynamic and lacking strong typing. As of February 14, 2017 dynamic was removed from SendGrid's official csharp library and support for .Net Standard was added.

StrongGrid includes a client that allows you to interact with all the "resources" in the SendGrid API (e.g.: send an email, manage lists, contacts and segments, search for contacts matching criteria, create API keys, etc.).

StrongGrid also includes a parser for webhook sent from SendGrid to your own WebAPI. This parser supports the two types of webhooks that SendGrid can post to your API: the Event Webhook and the Inbound Parse Webhook.

Since November 2017, StrongGrid also includes a "warmup engine" that allows you to warmup IP addresses using a custom schedule.

If you need information about how to setup the SendGrid webhooks, please consult the following resources:

  • Webhooks Overview
  • Guide to debug webhooks
  • Setting up the inbound parse webhook

Installation

The easiest way to include StrongGrid in your C# project is by adding the nuget package to your project:

PM> Install-Package StrongGrid

Once you have the StrongGrid library properly referenced in your project, add the following namespace:

using StrongGrid;

.NET framework support

StrongGrid currently supports:

  • .NET framework 4.8
  • any framework supporting .NET Standard 2.1 (which includes .NET 5.0 and all subsequent versions as well as some legacy versions such as .NET Core 3.x and ASP.NET Core 3.x).

Usage

Client

You declare your client variable like so:

csharp
var apiKey = "... your api key...";
var strongGridClient = new StrongGrid.Client(apiKey);

If you need to use a proxy, you can pass it to the Client:

csharp
var apiKey = "... your api key...";
var proxy = new WebProxy("http://myproxy:1234");
var strongGridClient = new StrongGrid.Client(apiKey, proxy);

Lifetime management

By default, the StrongGrid client creates a new instance of HttpClient in order to send requests to the SendGrid API. This means that the lifetime guidance for StrongGrid.Client is the same as the lifetime guidance for HttpClient. Microsoft's documentation states the following:

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

Keeping Microsoft's guidance in mind, my best advice to developers who are using StrongGrid is to avoid constantly instantiating new StrongGrid.Client because it can lead to socket exhaustion under heavy load.In my opinion, one of the best explanation of the problem with short-lived HTTP clients was written by Simon Simms back in August 2016 but there are many other similar articles you can find with a quick Google search.

Please note that StrongGrid.Client has a constructor that allows you to provide your own HttpClient wich means that you could instantiate a new StrongGrid.Client as often as you want as long as you provide your own HttpClient and you properly manage the lifetime of this HttpClient.

In summary:

  • It's best to instantiate the StrongGrid.Client once and re-use it.
  • You can instantiate a new StrongGrid.Client as often as you desire as long as you provide your own HttpClient and you properly manage the lifetime of this HttpClient.

Having said all this, there's an even better approach if you are using an IoC container (see next section).

Inversion of Control (IoC)

If you are using Microsoft.Extensions.DependencyInjection, the StrongGrid library contains a convenient extension method that will register and manage the litetime of the StrongGrid.Client as well as manage the underlying HttpClient, all with the goal of avoiding socket exhaustion. For other IoC containers (Autofac, SimpleInjector, Pure.DI, etc.), you'll need to register services manually using similar patterns.

  1. Here's an example showing how to register the StrongGrid client for .NET 8+ web apps:
csharp
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var sendGridApiKey = builder.Configuration["SendGridApiKey"]; // use your SendGrid API key
var strongGridHttpClientBuilder = builder.Services.AddStrongGrid(sendGridApiKey);
// ...
var app = builder.Build();
// ...
app.Run();

and here's how this StrongGrid client would be used in a service:

csharp
public class MyEmailService
{
    private readonly StrongGrid.IClient _strongGridClient; 
    
    public MyEmailService(StrongGrid.IClient strongGridClient)
    {
        _strongGridClient = strongGridClient;
    }
    
    public async Task SendEmailAsync()
    {
        await _strongGridClient.Mail.SendToSingleRecipientAsync(/* email details */);
    }
}
  1. Here's another example, this one for a console Applications & Worker Services (Using Generic Host):
csharp
var builder = Host.CreateApplicationBuilder(args);
var sendGridApiKey = builder.Configuration["SendGridApiKey"];
builder.Services.AddStrongGrid(sendGridApiKey);
var host = builder.Build();
var strongGridClient = host.Services.GetRequiredService();
await strongGridClient.Mail.SendToSingleRecipientAsync(/* email details */);
  1. Here's an example for simple console applications or utilities where you don't need the full Generic Host:
csharp
var services = new ServiceCollection();
services.AddStrongGrid("your-api-key");
var serviceProvider = services.BuildServiceProvider();
var client = serviceProvider.GetRequiredService();
await client.Mail.SendToSingleRecipientAsync(/* email details */);

Sending emails

One of the most common scenarios is to send transactional emails.

Here are a few examples:

…

Resources

You have access to numerous 'resources' (such as Contacts, Lists, Segments, Settings, SenderAuthentication, etc) off of the Client and each resource offers several methods such as retrieve, create, update, delete, etc.

Here are a few example:

…

Dynamic templates

In August 2018, SendGrid released a new feature in their API that allows you to use the Handlebars syntax to specify merge fields in your content. Using this powerful new feature in StrongGrid is very easy.

First, you must specify TemplateType.Dynamic when creating a new template like in this example:

csharp
var dynamicTemplate = await strongGridClient.Templates.CreateAsync("My dynamic template", TemplateType.Dynamic).ConfigureAwait(false);

Second, you create a version of your content where you use the Handlebars syntax to define the merge fields and you can also specify an optional "test data" that will be used by the SendGrid UI to show you a sample. Rest assured that this test data will never be sent to any recipient. The following code sample demonstrates creating a dynamic template version containing simple substitution for CreditBalance, deep object replacements for Customer.first_name and Customer.last_name and an iterator that displays information about multiple orders.

…

Finally, you can send an email to a recipient and specify the dynamic data that applies to them like so:

csharp
var dynamicData = new
{
	Customer = new
	{
		first_name = "Bob",
		last_name = "Smith"
	},
	CreditBalance = 56.78,
	Orders = new[]
	{
		new { item = "shoes", date = "2/1/2018" },
		new { item = "hat", date = "1/4/2018" }
	}
};
var to = new MailAddress("[email protected]", "Bob Smith");
var from = new MailAddress("[email protected]", "John Smith");
var messageId = await strongGridClient.Mail.SendToSingleRecipientAsync(to, from, dynamicTemplate.Id, dynamicData).ConfigureAwait(false);

Webhook Parser

Here's a basic example of a .net 6.0 API controller which parses the webhook from SendGrid:

…

Parsing a signed webhook

SendGrid has a feature called Signed Event Webhook Requests which you can enable under Settings > Mail Settings > Event Settings when logged in your SendGrid account. When this feature is enabled, SendGrid includes additional information with each webhook that allows you to verify that this webhook indeed originated from SendGrid and therefore can be trusted. Specifically, the webhook will include a "signature" and a "timestamp" and you must use these two values along with a public key that SendGrid generated when you enabled the feature to validate the data being submited to you. Please note that SendGrid sometimes refers to this value as a "verification key". In case you are curious and want to know more about the intricacies of validating the data, I invite you to read SendGrid's documentation on this topic.

However, if you want to avoid learning how to perform the validation and you simply want this validation to be conveniently performed for you, StrongGrid can help! The WebhookParser class has a method called ParseSignedEventsWebhookAsyncwhich will automatically validate the data and throw a security exception if validation fails. If the validation fails, you should consider the webhook data to be invalid. Here's how it works:

…

Warmup Engine

SendGrid already provides a way to warm up ip addresses but you have no control over this process. StrongGrid solves this issue by providing you a warmup engine that you can tailor to your needs.

Typical usage

…

The Send... methods return a WarmupResult object that will tell you whether the process is completed or not, and will also give you the messageId of the email sent using the IP pool (if applicable) and the messageId of the email sent using the default IP address (which is not being warmed up). The WarmupEngine will send emails using the IP pool until the daily volume limit is achieved and any remaining email will be sent using the default IP address. As you get close to your daily limit, it's possible that the Warmup engine may have to split a given "send" into two messages: one of which is sent using the ip pool a

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#emailsendgridsendgrid-apisendgrid-api-wrapper

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言