StrongGrid
Strongly typed library for the entire SendGrid v3 API, including webhooks
Install / Use
/learn @Jericho/StrongGridREADME
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:
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:
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:
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.
- Here's an example showing how to register the StrongGrid client for .NET 8+ web apps:
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:
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 */);
}
}
- Here's another example, this one for a console Applications & Worker Services (Using Generic Host):
var builder = Host.CreateApplicationBuilder(args);
var sendGridApiKey = builder.Configuration["SendGridApiKey"];
builder.Services.AddStrongGrid(sendGridApiKey);
var host = builder.Build();
var strongGridClient = host.Services.GetRequiredService<StrongGrid.IClient>();
await strongGridClient.Mail.SendToSingleRecipientAsync(/* email details */);
- Here's an example for simple console applications or utilities where you don't need the full Generic Host:
var services = new ServiceCollection();
services.AddStrongGrid("your-api-key");
var serviceProvider = services.BuildServiceProvider();
var client = serviceProvider.GetRequiredService<StrongGrid.IClient>();
await client.Mail.SendToSingleRecipientAsync(/* email details */);
Sending emails
One of the most common scenarios is to send transactional emails.
Here are a few examples:
// Send an email to a single recipient
var messageId = await strongGridClient.Mail.SendToSingleRecipientAsync(to, from, subject, html, text).ConfigureAwait(false);
// Send an email to multiple recipients
var messageId = await strongGridClient.Mail.SendToMultipleRecipientsAsync(new[] { to1, to2, to3 }, from, subject, html, text).ConfigureAwait(false);
// Include attachments when sending an email
var attachments = new[]
{
Attachment.FromLocalFile(@"C:\MyDocuments\MySpreadsheet.xlsx"),
Attachment.FromLocalFile(@"C:\temp\Headshot.jpg")
};
var messageId = await strongGridClient.Mail.SendToSingleRecipientAsync(to, from, subject, html, text, attachments: attachments).ConfigureAwait(false);
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:
// Import a new contact or update existing contact if a match is found
var importJobId = await client.Contacts.UpsertAsync(email, firstName, lastName, addressLine1, addressLine2, city, stateOrProvince, country, postalCode, alternateEmails, customFields, null, cancellationToken).ConfigureAwait(false);
// Import several new contacts or update existing contacts when a match is found
var contacts = new[]
{
new Models.Contact("dum
Related Skills
node-connect
349.0kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
109.4kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
349.0kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
349.0kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
