StrongGrid 0.110.0

dotnet add package StrongGrid --version 0.110.0                
NuGet\Install-Package StrongGrid -Version 0.110.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="StrongGrid" Version="0.110.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add StrongGrid --version 0.110.0                
#r "nuget: StrongGrid, 0.110.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install StrongGrid as a Cake Addin
#addin nuget:?package=StrongGrid&version=0.110.0

// Install StrongGrid as a Cake Tool
#tool nuget:?package=StrongGrid&version=0.110.0                

StrongGrid

Discussions at https://github.com/Jericho/StrongGrid/discussions FOSSA Status License Sourcelink

Build status Tests Coverage Status CodeFactor

Release Notes NuGet (stable) MyGet (prerelease)
GitHub release NuGet Version MyGet Pre Release

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 suport

StrongGrid supports the 4.8, 6.0 and 7.0 .NET frameworks as well as any framework supporting .NET Standard 2.1 (which includes .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);

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);

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("dummy1@hotmail.com", "John", "Doe"),
	new Models.Contact("dummy2@hotmail.com", "John", "Smith"),
	new Models.Contact("dummy3@hotmail.com", "Bob", "Smith")
};
var importJobId = await client.Contacts.UpsertAsync(contacts, null, cancellationToken).ConfigureAwait(false);

// Send an email
await strongGridClient.Mail.SendToSingleRecipientAsync(to, from, subject, htmlContent, textContent);

// Retreive all the API keys in your account
var apiKeys = await strongGridClient.ApiKeys.GetAllAsync();

// Add an email address to a suppression group
await strongGridClient.Suppressions.AddAddressToUnsubscribeGroupAsync(groupId, "test1@example.com");

// Get statistics between the two specific dates
var globalStats = await strongGridClient.Statistics.GetGlobalStatisticsAsync(startDate, endDate);

// Create a new email template
var template = await strongGridClient.Templates.CreateAsync("My template");

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:

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.

var subject = "Dear {{Customer.first_name}}";
var htmlContent = @"
	<html>
		<body>
			Hello {{Customer.first_name}} {{Customer.last_name}}. 
			You have a credit balance of {{CreditBalance}}<br/>
			<ol>
			{{#each Orders}}
				<li>You ordered: {{this.item}} on: {{this.date}}</li>
			{{/each}}
			</ol>
		</body>
	</html>";
var textContent = "... this is the text content ...";
var testData = new
{
	Customer = new
	{
		first_name = "aaa",
		last_name = "aaa"
	},
	CreditBalance = 99.88,
	Orders = new[]
	{
		new { item = "item1", date = "1/1/2018" },
		new { item = "item2", date = "1/2/2018" },
		new { item = "item3", date = "1/3/2018" }
	}
};
await strongGridClient.Templates.CreateVersionAsync(dynamicTemplate.Id, "Version 1", subject, htmlContent, textContent, true, EditorType.Code, testData).ConfigureAwait(false);

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("bobsmith@hotmail.com", "Bob Smith");
var from = new MailAddress("test@example.com", "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:

using Microsoft.AspNetCore.Mvc;
using StrongGrid;

namespace WebApplication1.Controllers
{
	[Route("api/[controller]")]
	[ApiController]
	public class SendGridWebhooksController : ControllerBase
	{
		[HttpPost]
		[Route("Events")]
		public async Task<IActionResult> ReceiveEvents()
		{
			var parser = new WebhookParser();
			var events = await parser.ParseEventsWebhookAsync(Request.Body).ConfigureAwait(false);

			// ... do something with the events ...

			return Ok();
		}

		[HttpPost]
		[Route("InboundEmail")]
		public async Task<IActionResult> ReceiveInboundEmail()
		{
			var parser = new WebhookParser();
			var inboundEmail = await parser.ParseInboundEmailWebhookAsync(Request.Body).ConfigureAwait(false);

			// ... do something with the inbound email ...

			return Ok();
		}
    }
}

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:

using Microsoft.AspNetCore.Mvc;
using StrongGrid;
using System.Security;

namespace WebApplication1.Controllers
{
	[Route("api/[controller]")]
	[ApiController]
	public class SendGridWebhooksController : ControllerBase
	{
		[HttpPost]
		[Route("SignedEvents")]
		public async Task<IActionResult> ReceiveSignedEvents()
		{
			// Get your public key
			var apiKey = "... your api key...";
			var strongGridClient = new StrongGrid.Client(apiKey);
			var publicKey = await strongGridClient.WebhookSettings.GetSignedEventsPublicKeyAsync().ConfigureAwait(false);

			// Get the signature and the timestamp from the request headers
			var signature = Request.Headers[WebhookParser.SIGNATURE_HEADER_NAME]; // SIGNATURE_HEADER_NAME is a convenient constant provided so you don't have to remember the name of the header
			var timestamp = Request.Headers[WebhookParser.TIMESTAMP_HEADER_NAME]; // TIMESTAMP_HEADER_NAME is a convenient constant provided so you don't have to remember the name of the header

			// Parse the events. The signature will be automatically validated and a security exception thrown if unable to validate
			try
			{
				var parser = new WebhookParser();
				var events = await parser.ParseSignedEventsWebhookAsync(Request.Body, publicKey, signature, timestamp).ConfigureAwait(false);

				// ... do something with the events...
			}
			catch (SecurityException e)
			{
				// ... unable to validate the data...
			}

			return Ok();
		}
	}
}

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
// Prepare the warmup engine
var poolName = "warmup_pool";
var dailyVolumePerIpAddress = new[] { 50, 100, 500, 1000 };
var resetDays = 1; // Should be 1 if you send on a daily basis, should be 2 if you send every other day, should be 7 if you send on a weekly basis, etc.
var warmupSettings = new WarmupSettings(poolName, dailyVolumePerIpAddress, resetDays);
var warmupEngine = new WarmupEngine(warmupSettings, client);

// This is a one-time call to create the IP pool that will be used to warmup the IP addresses
var ipAddresses = new[] { "168.245.123.132", "168.245.123.133" };
await warmupEngine.PrepareWithExistingIpAddressesAsync(ipAddresses, CancellationToken.None).ConfigureAwait(false);

// Send emails using any of the following methods
var result = warmupEngine.SendToSingleRecipientAsync(...);
var result = warmupEngine.SendToMultipleRecipientsAsync(...);
var result = warmupEngine.SendAsync(...);

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 and the other one sent using the default ip address. Let's use an example to illustrate: let's say that you have 15 emails left before you reach your daily warmup limit and you try to send an email to 20 recipients. In this scenario the first 15 emails will be sent using the warmup ip pool and the remaining 5 emails will be sent using the default ip address.

More advanced usage

Recommended daily volume: If you are unsure what daily limits to use, SendGrid has provided a recommended schedule and StrongGrid provides a convenient method to use the recommended schedule tailored to the number of emails you expect to send in a typical day. All you have to do is come up with a rough estimate of your daily volume and StrongGrid can configure the appropriate warmup settings. Here's an example:

var poolName = "warmup_pool";
var estimatedDailyVolume = 50000; // Should be your best guess: how many emails you will be sending in a typical day
var resetDays = 1; // Should be 1 if you send on a daily basis, should be 2 if you send every other day, should be 7 if you send on a weekly basis, etc.
var warmupSettings = WarmupSettings.FromSendGridRecomendedSettings(poolName, estimatedDailyVolume, resetDays);

Progress repository: By default StrongGrid's WarmupEngine will write progress information in a file on your computer's temp folder but you can override this settings. You can change the folder where this file is saved and you can also decide to use a completely different repository. Out of the box, StrongGrid provides FileSystemWarmupProgressRepository and MemoryWarmupProgressRepository. It also provides an interface called IWarmupProgressRepository which allows you to write your own implementation to save the progress data to a location more suitable to you such as a database, Azure, AWS, etc. Please note that MemoryWarmupProgressRepository in intended to be used for testing and we don't recommend using it in production. The main reason for this recommendation is that the data is stored in memory and is lost when your computer is restarted. This means that your warmup process would start all over from day 1 each time you computer is rebooted.

// You select one of the following repositories available out of the box:
var warmupProgressRepository = new MemoryWarmupProgressRepository();
var warmupProgressRepository = new FileSystemWarmupProgressRepository();
var warmupProgressRepository = new FileSystemWarmupProgressRepository(@"C:\temp\myfolder\");
var warmupEngine = new WarmupEngine(warmupSettings, client, warmupProgressRepository);

Purchase new IP Addresses: You can purchase new IP addresses using SendGrid' UI, but StrongGrid's WarmupEngine makes it even easier. Rather than invoking PrepareWithExistingIpAddressesAsync (as demonstrated previously), you can invoke PrepareWithNewIpAddressesAsync and StrongGrid will take care of adding new ip addresses to your account and add them to a new IP pool ready for warmup. As a reminder, please note that the PrepareWithExistingIpAddressesAsync and PrepareWithNewIpAddressesAsync should only be invoked once. Invoking either method a second time would result in an exception due to the fact that the IP pool has already been created.

var howManyAddresses = 2; // How many ip addresses do you want to purchase?
var subusers = new[] { "your_subuser" }; // The subusers you authorize to send emails on the new ip addresses
await warmupEngine.PrepareWithNewIpAddressesAsync(howManyAddresses, subusers, CancellationToken.None).ConfigureAwait(false);

End of warmup process: When the process is completed, the IP pool is deleted and the warmed up IP address(es) are returned to the default pool. You can subsequently invoke the strongGridClient.Mail.SendAsync(...) method to send your emails.

License

FOSSA Status

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
.NET Framework net48 is compatible.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (8)

Showing the top 5 NuGet packages that depend on StrongGrid:

Package Downloads
AuthScape.SendGrid

Package Description

AuthScape.TicketSystem

Package Description

Cake.SendGrid

Cake Build addin to provide Aliases for sending emails via SendGrid.

CodeStream.Comms.Messages

CodeStream Communication Messages infrastructure code for applications

Magnet.Providers.SendGrid

Framework to receive messages like Sms and Emails in integration tests.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on StrongGrid:

Repository Stars
SciSharp/BotSharp
AI Multi-Agent Framework in .NET
Version Downloads Last updated
0.110.0 618 11/17/2024
0.109.0 79,964 6/19/2024
0.108.0 19,179 5/26/2024
0.107.0 24,549 4/18/2024
0.106.0 29,775 2/16/2024
0.105.0 11,686 2/1/2024
0.104.0 10,824 1/19/2024
0.103.0 14,994 1/8/2024
0.102.0 13,122 11/18/2023
0.101.0 93,974 6/2/2023
0.100.0 6,023 6/1/2023
0.99.0 240 6/1/2023
0.98.0 140,419 1/20/2023
0.97.0 10,655 1/12/2023
0.96.0 32,066 12/2/2022
0.95.1 30,386 11/13/2022
0.94.0 36,929 9/30/2022
0.93.0 12,339 9/13/2022
0.92.0 10,981 8/22/2022
0.91.0 40,190 6/26/2022
0.90.0 32,406 4/21/2022
0.89.0 33,487 3/21/2022
0.88.2 25,623 3/15/2022
0.88.1 666 3/14/2022
0.88.0 7,596 2/5/2022
0.87.0 3,644 1/18/2022
0.86.0 678 1/14/2022
0.85.0 21,892 1/14/2022
0.84.0 64,286 11/25/2021
0.83.0 1,953 11/11/2021
0.82.0 122,392 5/23/2021
0.81.0 4,535 5/9/2021
0.80.0 762 5/5/2021
0.79.0 94,398 4/27/2021
0.78.0 1,612 4/15/2021
0.77.0 15,380 4/4/2021
0.76.0 55,688 1/20/2021
0.75.0 117,879 11/28/2020
0.74.0 1,052 11/26/2020
0.73.0 90,509 10/3/2020
0.72.1 64,094 9/15/2020
0.71.0 19,545 8/7/2020
0.70.0 34,408 6/24/2020
0.69.0 41,008 5/10/2020
0.68.0 14,322 4/13/2020
0.67.0 8,369 4/3/2020
0.66.0 28,882 3/26/2020
0.65.0 9,302 3/11/2020
0.64.0 6,857 3/6/2020
0.63.1 35,680 1/3/2020
0.62.0 24,798 11/29/2019
0.61.0 32,630 9/22/2019
0.60.0 64,444 7/7/2019
0.59.0 7,210 6/21/2019
0.58.0 3,760 6/6/2019
0.57.1 1,109 6/3/2019
0.56.1 928 5/30/2019
0.56.0 37,862 5/28/2019
0.55.0 15,532 5/16/2019
0.54.0 5,975 5/2/2019
0.53.0 3,743 4/23/2019
0.52.0 944 4/19/2019
0.51.0 3,298 4/14/2019
0.50.2 49,869 3/27/2019
0.50.1 948 3/27/2019
0.50.0 1,756 3/11/2019
0.49.1 15,172 11/9/2018
0.49.0 4,457 10/25/2018
0.48.0 24,177 8/20/2018
0.47.3 2,531 8/15/2018
0.47.2 1,054 8/14/2018
0.47.1 1,062 8/14/2018
0.47.0 2,708 8/4/2018
0.46.0 2,439 7/27/2018
0.45.0 14,553 6/12/2018
0.44.0 5,030 5/23/2018
0.43.0 11,289 5/5/2018
0.42.0 1,139 5/4/2018
0.41.0 1,227 5/2/2018
0.40.0 3,329 4/18/2018
0.39.0 1,937 4/9/2018
0.38.0 1,729 4/3/2018
0.37.0 2,513 3/20/2018
0.36.0 5,444 2/18/2018
0.35.0 8,840 1/17/2018
0.34.0 6,449 11/20/2017
0.33.0 3,058 11/16/2017
0.32.0 3,146 10/27/2017
0.31.0 4,333 10/4/2017
0.30.0 16,113 10/2/2017
0.29.0 2,406 9/17/2017
0.28.0 25,948 6/3/2017
0.27.0 6,460 4/24/2017
0.26.0 2,462 3/29/2017
0.25.0 1,573 3/24/2017
0.24.0 1,236 3/19/2017
0.23.0 1,418 3/9/2017
0.22.0 1,597 2/21/2017
0.21.0 1,282 2/19/2017
0.20.0 1,311 2/18/2017
0.19.0 1,298 2/13/2017
0.18.3 1,530 2/3/2017
0.18.2 1,229 2/2/2017
0.18.1 2,222 1/28/2017
0.18.0 11,509 1/5/2017
0.17.0 3,781 12/14/2016
0.16.0 2,959 12/7/2016
0.15.0 1,232 12/2/2016
0.14.0 1,238 11/30/2016
0.13.0 1,199 11/29/2016
0.12.0 1,200 11/26/2016
0.11.0 1,155 11/22/2016
0.10.0 1,400 11/14/2016
0.9.0 1,205 11/11/2016
0.8.0 1,223 11/10/2016
0.7.2 1,319 10/27/2016
0.7.1 1,138 10/27/2016
0.7.0 1,196 10/27/2016
0.6.0 1,208 10/25/2016
0.5.0 1,182 10/22/2016
0.4.0 1,179 10/20/2016
0.3.0 1,194 10/19/2016
0.2.0 1,192 10/17/2016
0.1.0 1,266 10/17/2016