### Install StrongGrid NuGet Package Source: https://github.com/jericho/stronggrid/blob/develop/README.md Use this command in the Package Manager Console to install the StrongGrid library. ```powershell PM> Install-Package StrongGrid ``` -------------------------------- ### Initialize and Prepare Warmup Engine Source: https://github.com/jericho/stronggrid/blob/develop/README.md Prepare the warmup engine by defining pool settings and existing IP addresses. This is a one-time setup for the IP pool. ```csharp // 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); ``` -------------------------------- ### Create Email Template with StrongGrid Source: https://github.com/jericho/stronggrid/blob/develop/README.md Example for creating a new email template with a given name. ```csharp // Create a new email template var template = await strongGridClient.Templates.CreateAsync("My template"); ``` -------------------------------- ### Get Statistics with StrongGrid Source: https://github.com/jericho/stronggrid/blob/develop/README.md Example for retrieving global statistics within a specified date range. ```csharp // Get statistics between the two specific dates var globalStats = await strongGridClient.Statistics.GetGlobalStatisticsAsync(startDate, endDate); ``` -------------------------------- ### Retrieve API Keys with StrongGrid Source: https://github.com/jericho/stronggrid/blob/develop/README.md Example for retrieving all API keys associated with your StrongGrid account. ```csharp // Retreive all the API keys in your account var apiKeys = await strongGridClient.ApiKeys.GetAllAsync(); ``` -------------------------------- ### Send Email with StrongGrid Source: https://github.com/jericho/stronggrid/blob/develop/README.md A basic example for sending a single email using the StrongGrid client. ```csharp // Send an email await strongGridClient.Mail.SendToSingleRecipientAsync(to, from, subject, htmlContent, textContent); ``` -------------------------------- ### Prepare IP Pool with New IP Addresses Source: https://github.com/jericho/stronggrid/blob/develop/README.md Automate the purchase and setup of new IP addresses for warmup. This method adds new IPs to your account and prepares them in a new IP pool. This should only be invoked once per IP pool. ```csharp 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); ``` -------------------------------- ### Manage Suppressions with StrongGrid Source: https://github.com/jericho/stronggrid/blob/develop/README.md Example for adding an email address to a specific unsubscribe group. ```csharp // Add an email address to a suppression group await strongGridClient.Suppressions.AddAddressToUnsubscribeGroupAsync(groupId, "test1@example.com"); ``` -------------------------------- ### Send Transactional Emails with StrongGrid Source: https://github.com/jericho/stronggrid/blob/develop/README.md Examples for sending transactional emails. Use SendToSingleRecipientAsync for one recipient and SendToMultipleRecipientsAsync for multiple. Attachments can be included using the attachments parameter. ```csharp // Send an email to a single recipient var messageId = await strongGridClient.Mail.SendToSingleRecipientAsync(to, from, subject, html, text).ConfigureAwait(false); ``` ```csharp // Send an email to multiple recipients var messageId = await strongGridClient.Mail.SendToMultipleRecipientsAsync(new[] { to1, to2, to3 }, from, subject, html, text).ConfigureAwait(false); ``` ```csharp // 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); ``` -------------------------------- ### Manage Contacts with StrongGrid Source: https://github.com/jericho/stronggrid/blob/develop/README.md Examples for managing contacts. Use UpsertAsync to import new contacts or update existing ones. This method can handle single contacts or arrays of contacts. ```csharp // 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); ``` ```csharp // 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); ``` -------------------------------- ### Parse SendGrid Events Webhook Source: https://github.com/jericho/stronggrid/blob/develop/README.md Use the WebhookParser to parse incoming events from SendGrid. This example is for a .NET 6.0 API controller. ```csharp using Microsoft.AspNetCore.Mvc; using StrongGrid; namespace WebApplication1.Controllers { [Route("api/[controller]")] [ApiController] public class SendGridWebhooksController : ControllerBase { [HttpPost] [Route("Events")] public async Task 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 ReceiveInboundEmail() { var parser = new WebhookParser(); var inboundEmail = await parser.ParseInboundEmailWebhookAsync(Request.Body).ConfigureAwait(false); // ... do something with the inbound email ... return Ok(); } } } ``` -------------------------------- ### Get Global Statistics Source: https://github.com/jericho/stronggrid/blob/develop/README.md Retrieves global statistics for email activity within a specified date range. ```APIDOC ## Get Global Statistics ### Description Retrieves global statistics for email sending and delivery performance between two specified dates. ### Method `GET` (Implied by SDK method) ### Endpoint `/stats` (Implied by SDK method) ### Parameters #### Path Parameters None #### Query Parameters - **startDate** (date) - The start date for the statistics period. - **endDate** (date) - The end date for the statistics period. ### Request Example ```csharp var startDate = new DateTime(2023, 1, 1); var endDate = new DateTime(2023, 1, 31); var globalStats = await strongGridClient.Statistics.GetGlobalStatisticsAsync(startDate, endDate); ``` ### Response #### Success Response (200) - **globalStats** (object) - An object containing global statistics. ``` -------------------------------- ### Initialize StrongGrid Client with Proxy Source: https://github.com/jericho/stronggrid/blob/develop/README.md Configure the StrongGrid client to use a proxy server by providing a WebProxy instance during initialization. ```csharp var apiKey = "... your api key..."; var proxy = new WebProxy("http://myproxy:1234"); var strongGridClient = new StrongGrid.Client(apiKey, proxy); ``` -------------------------------- ### Initialize StrongGrid Client Source: https://github.com/jericho/stronggrid/blob/develop/README.md Instantiate the StrongGrid client with your API key. It's recommended to reuse this client instance to avoid socket exhaustion. ```csharp var apiKey = "... your api key..."; var strongGridClient = new StrongGrid.Client(apiKey); ``` -------------------------------- ### Customize Warmup Progress Repository Source: https://github.com/jericho/stronggrid/blob/develop/README.md StrongGrid allows customization of where warmup progress is stored. You can use the provided FileSystem or Memory repositories, or implement your own IWarmupProgressRepository for custom storage like databases or cloud services. MemoryWarmupProgressRepository is not recommended for production due to data loss on restart. ```csharp // You select one of the following repositories available out of the box: var warmupProgressRepository = new MemoryWarmupProgressRepository(); ``` ```csharp var warmupProgressRepository = new FileSystemWarmupProgressRepository(); ``` ```csharp var warmupProgressRepository = new FileSystemWarmupProgressRepository(@"C:\\temp\\myfolder\\"); ``` ```csharp var warmupEngine = new WarmupEngine(warmupSettings, client, warmupProgressRepository); ``` -------------------------------- ### Configure SendGrid Recommended Warmup Settings Source: https://github.com/jericho/stronggrid/blob/develop/README.md Use this method to automatically configure warmup settings based on SendGrid's recommendations. Provide an estimated daily volume and the reset days for your sending schedule. ```csharp 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); ``` -------------------------------- ### Send Emails Using Warmup Engine Source: https://github.com/jericho/stronggrid/blob/develop/README.md Send emails using different methods provided by the WarmupEngine. The engine manages distribution between the warmup IP pool and the default IP address based on daily volume limits. ```csharp // Send emails using any of the following methods var result = warmupEngine.SendToSingleRecipientAsync(...); var result = warmupEngine.SendToMultipleRecipientsAsync(...); var result = warmupEngine.SendAsync(...); ``` -------------------------------- ### Register StrongGrid for Simple Console Applications Source: https://github.com/jericho/stronggrid/blob/develop/README.md Manually register the StrongGrid client using ServiceCollection for simple console applications or utilities without the 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 */); ``` -------------------------------- ### Use StrongGrid Client in a Service (.NET Web Apps) Source: https://github.com/jericho/stronggrid/blob/develop/README.md Inject the StrongGrid client into your services via the constructor when using dependency injection. ```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 */); } } ``` -------------------------------- ### Register StrongGrid for Console Applications & Worker Services Source: https://github.com/jericho/stronggrid/blob/develop/README.md Configure the Generic Host to register the StrongGrid client for use in console applications and worker services. ```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 */); ``` -------------------------------- ### Register StrongGrid for .NET 8+ Web Apps Source: https://github.com/jericho/stronggrid/blob/develop/README.md Use this extension method with Microsoft.Extensions.DependencyInjection to register and manage the StrongGrid client and its underlying HttpClient. ```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(); ``` -------------------------------- ### Add StrongGrid Namespace Source: https://github.com/jericho/stronggrid/blob/develop/README.md Include this using statement at the top of your C# files to access StrongGrid functionalities. ```csharp using StrongGrid; ``` -------------------------------- ### Create Dynamic Template Source: https://github.com/jericho/stronggrid/blob/develop/README.md Specify TemplateType.Dynamic when creating a new template to enable dynamic content. ```csharp var dynamicTemplate = await strongGridClient.Templates.CreateAsync("My dynamic template", TemplateType.Dynamic).ConfigureAwait(false); ``` -------------------------------- ### Retrieve All API Keys Source: https://github.com/jericho/stronggrid/blob/develop/README.md Retrieves a list of all API keys associated with the account. ```APIDOC ## Retrieve All API Keys ### Description Fetches all API keys that have been generated for the account. ### Method `GET` (Implied by SDK method) ### Endpoint `/api-keys` (Implied by SDK method) ### Parameters None ### Request Example ```csharp var apiKeys = await strongGridClient.ApiKeys.GetAllAsync(); ``` ### Response #### Success Response (200) - **apiKeys** (array) - An array of API key objects. ``` -------------------------------- ### Create Email Template Source: https://github.com/jericho/stronggrid/blob/develop/README.md Creates a new email template with a specified name. ```APIDOC ## Create Email Template ### Description Creates a new email template. The template can be used later for sending personalized emails. ### Method `POST` (Implied by SDK method) ### Endpoint `/templates` (Implied by SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - The name for the new email template. ### Request Example ```csharp var template = await strongGridClient.Templates.CreateAsync("My template"); ``` ### Response #### Success Response (200) - **template** (object) - The newly created template object. ``` -------------------------------- ### Create Dynamic Template Version Source: https://github.com/jericho/stronggrid/blob/develop/README.md Create a version of a dynamic template using Handlebars syntax for merge fields and optional test data for previewing in the SendGrid UI. This data is not sent to recipients. ```csharp var subject = "Dear {{Customer.first_name}}"; var htmlContent = @" Hello {{Customer.first_name}} {{Customer.last_name}}. You have a credit balance of {{CreditBalance}}
    {{#each Orders}}
  1. You ordered: {{this.item}} on: {{this.date}}
  2. {{/each}}
"; 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); ``` -------------------------------- ### Send Email with Dynamic Template Source: https://github.com/jericho/stronggrid/blob/develop/README.md Send an email using a dynamic template by providing recipient-specific dynamic data. Ensure the 'to', 'from', and template ID are correctly specified. ```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("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); ``` -------------------------------- ### Parse and Validate Signed SendGrid Webhooks Source: https://github.com/jericho/stronggrid/blob/develop/README.md Use `WebhookParser.ParseSignedEventsWebhookAsync` to automatically validate the signature and timestamp of incoming SendGrid webhooks. This method throws a `SecurityException` if validation fails, ensuring data integrity. Ensure you have your SendGrid API key to retrieve the public key. ```csharp 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 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(); } } } ``` -------------------------------- ### Send Email to Multiple Recipients Source: https://github.com/jericho/stronggrid/blob/develop/README.md Sends an email to multiple recipients simultaneously. Each recipient receives their own copy of the email. ```APIDOC ## Send Email to Multiple Recipients ### Description Sends an email to a list of recipients. Each recipient in the provided array will receive the email. ### Method `POST` (Implied by SDK method) ### Endpoint `/mail/send` (Implied by SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **recipients** (array of strings) - An array of recipient email addresses. - **from** (string) - The sender's email address. - **subject** (string) - The subject of the email. - **html** (string) - The HTML content of the email. - **text** (string) - The plain text content of the email. ### Request Example ```csharp var to1 = "recipient1@example.com"; var to2 = "recipient2@example.com"; var to3 = "recipient3@example.com"; var from = "sender@example.com"; var subject = "Test Subject"; var html = "

Hello!

"; var text = "Hello!"; var messageId = await strongGridClient.Mail.SendToMultipleRecipientsAsync(new[] { to1, to2, to3 }, from, subject, html, text).ConfigureAwait(false); ``` ### Response #### Success Response (200) - **messageId** (string) - The unique identifier for the sent message. ``` -------------------------------- ### Upsert Contact Source: https://github.com/jericho/stronggrid/blob/develop/README.md Imports a new contact or updates an existing contact if a match is found based on email address. ```APIDOC ## Upsert Contact ### Description Imports a new contact into the system or updates an existing contact if an email address match is found. Allows for detailed contact information including address and custom fields. ### Method `POST` (Implied by SDK method) ### Endpoint `/contacts` (Implied by SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **email** (string) - The email address of the contact. - **firstName** (string) - The first name of the contact. - **lastName** (string) - The last name of the contact. - **addressLine1** (string) - The first line of the contact's address. - **addressLine2** (string) - The second line of the contact's address. - **city** (string) - The city of the contact's address. - **stateOrProvince** (string) - The state or province of the contact's address. - **country** (string) - The country of the contact's address. - **postalCode** (string) - The postal code of the contact's address. - **alternateEmails** (array of strings) - Optional. Alternate email addresses for the contact. - **customFields** (object) - Optional. Key-value pairs for custom contact fields. ### Request Example ```csharp var importJobId = await client.Contacts.UpsertAsync("email@example.com", "John", "Doe", "123 Main St", null, "Anytown", "CA", "USA", "12345", null, null, null, CancellationToken.None).ConfigureAwait(false); ``` ### Response #### Success Response (200) - **importJobId** (string) - The ID of the import job. ``` ```APIDOC ## Upsert Multiple Contacts ### Description Imports multiple new contacts or updates existing contacts when a match is found. This method accepts an array of contact objects. ### Method `POST` (Implied by SDK method) ### Endpoint `/contacts` (Implied by SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **contacts** (array of Contact objects) - An array of contact objects to upsert. ### Request Example ```csharp 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.None).ConfigureAwait(false); ``` ### Response #### Success Response (200) - **importJobId** (string) - The ID of the import job. ``` -------------------------------- ### Send Email to Single Recipient Source: https://github.com/jericho/stronggrid/blob/develop/README.md Sends an email to a single recipient. Supports plain text and HTML content, and can include attachments. ```APIDOC ## Send Email to Single Recipient ### Description Sends an email to a single recipient with specified subject, HTML content, and text content. Attachments can optionally be included. ### Method `POST` (Implied by SDK method) ### Endpoint `/mail/send` (Implied by SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **to** (string) - The recipient's email address. - **from** (string) - The sender's email address. - **subject** (string) - The subject of the email. - **html** (string) - The HTML content of the email. - **text** (string) - The plain text content of the email. - **attachments** (array of Attachment objects) - Optional. Attachments to include with the email. ### Request Example ```csharp var to = "recipient@example.com"; var from = "sender@example.com"; var subject = "Test Subject"; var html = "

Hello!

"; var text = "Hello!"; var messageId = await strongGridClient.Mail.SendToSingleRecipientAsync(to, from, subject, html, text).ConfigureAwait(false); ``` ### Response #### Success Response (200) - **messageId** (string) - The unique identifier for the sent message. ``` -------------------------------- ### Add Address to Unsubscribe Group Source: https://github.com/jericho/stronggrid/blob/develop/README.md Adds a specific email address to a specified unsubscribe group. ```APIDOC ## Add Address to Unsubscribe Group ### Description Adds a given email address to a specified suppression group, preventing emails from being sent to that address. ### Method `POST` (Implied by SDK method) ### Endpoint `/groups/{groupId}/addresses` (Implied by SDK method) ### Parameters #### Path Parameters - **groupId** (integer) - The ID of the unsubscribe group. #### Query Parameters None #### Request Body - **email** (string) - The email address to add to the unsubscribe group. ### Request Example ```csharp await strongGridClient.Suppressions.AddAddressToUnsubscribeGroupAsync(groupId, "test1@example.com"); ``` ### Response #### Success Response (200) No specific response body is detailed, indicating a successful operation. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.