SendGrid is a pretty good ESP and has a nice API, it also has a free tier available through the Azure Portal. The C# library for it available through NuGet makes it easy to call the API but the documentation on GitHub is a bit lacking.
Below is some basic code for sending an email to a preconfigured template with placeholders.
public static async Task SendQaEmailAsync(SendGridConfig sendGridConfig, List<QaCount> qaCounts, DateTime runDateTime)
{
SendGridClient sendGridClient = new SendGridClient(sendGridConfig.ApiKey);
Dictionary<string, object> replacements = new Dictionary<string, object>();
replacements.Add("RunDate", runDateTime.ToString("dd/MM/yyyy HH:mm:ss"));
replacements.Add("QaCounts", qaCounts);
SendGridMessage sendGridMessage = MailHelper.CreateSingleTemplateEmailToMultipleRecipients(
new EmailAddress(sendGridConfig.From),
sendGridConfig.To.Select(x => new EmailAddress { Email = x }).ToList(),
sendGridConfig.TemplateId,
replacements
);
sendGridMessage.Subject = sendGridConfig.SubjectLine;
Response sendGridResponse = await sendGridClient.SendEmailAsync(sendGridMessage);
}
SendGrid works with Handlebars.js to allow you to use more complex logic in your templates such as iterating over the items in an array within an object.
In the above example I am adding a RunDate property and a list of QaCount objects to the dynamic property object that’s sent to SendGrid, this looks like the below.
{
"RunDate": "17/12/2019 09:32:56",
"QaCounts": [
{
"FileName": "File1.txt",
"FileVolume": 23
},
{
"FileName": "File2.txt",
"FileVolume": 99
},
]
}
One thing to note is that the variable names in SendGrid are case sensitive so if you’re passing through an object the properties will be serialized with the casing of the model and not converted to camel casing (there may be serialization settings but I haven’t found them yet).
0 Comments