适用于整个 SendGrid v3 API(包括 Webhooks)的强类型库
| Release Notes | NuGet (stable) | Feedz.IO (prerelease) |
|---|---|---|
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:
The easiest way to include StrongGrid in your C# project is by adding the nuget package to your project:
PM> Install-Package StrongGridOnce you have the StrongGrid library properly referenced in your project, add the following namespace:
using StrongGrid;StrongGrid currently supports:
.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).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);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:
Having said all this, there's an even better approach if you are using an IoC container (see next section).
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.
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 */);
}
}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 */);var services = new ServiceCollection();
services.AddStrongGrid("your-api-key");
var serviceProvider = services.BuildServiceProvider();
var client = serviceProvider.GetRequiredService();
await client.Mail.SendToSingleRecipientAsync(/* email details */);One of the most common scenarios is to send transactional emails.
Here are a few examples:
…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:
…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:
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:
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);Here's a basic example of a .net 6.0 API controller which parses the webhook from SendGrid:
…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:
…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.
…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,或尚未同步最近议题。