SendGrid guide: Integrating SendGrid in .NET Core MVC application, using templates and providing dynamic data

Praveen Korni
5 min readMay 23, 2021

--

TWILLIO SendGrid

Traditionally emails were sent using the SMTP but since .NET no more supports sending emails through SMTP, Twillio SendGrid is probably the best option for sending emails. SendGrid provides us with all the necessary tools to effortlessly send emails through our .NET Core MVC Application.

This document will help you to send emails from your .NET Core MVC application and will guide you through each step from scratch to finish.

  1. Sign-up for free/ making a SendGrid account.
  2. Getting an API key
  3. Testing the API key in an console application
  4. Integrating SendGrid in .NET Core MVC application, using templates and providing dynamic data

Sign-up for free/ making a SendGrid account

Basic first step is to go to the official SendGrid website. The home page would look similar to this.

Next step is to click on the “start for free” button on the home page

On clicking it, it will take you to the signup page where you can enter a valid email address and a 16 digit password (prefer google created passwords as they are not easy to crack also make sure you remember them) and then click on “Create account button”.

This action should now have taken you to a form, fill it completely and make sure you enter only valid data.

Whola! You have now successfully created an account on SendGrid.

Getting an API key

  1. Once you’re logged in successfully, move to the Integrate page, opt the Web API
  2. Select your preferred language of development (C#)
  3. In the next page, give your SendGrid api key a name and select on create key

4. Copy the key displayed over there and safely keep the API key name and the key noted.

5. Click on the verify integration button at the end of the page.

Testing the API key in a console application.

Install the following packages using the nuget packet manager:

using SendGrid;
using SendGrid.Helpers.Mail;
using Newtonsoft.json;

Make a new console application and add the following code block in it.

// using SendGrid’s C# Library
// https://github.com/sendgrid/sendgrid-csharp
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.Threading.Tasks;
namespace Example
{
internal class Example
{
private static void Main()
{
Execute().Wait();
}
static async Task Execute()
{
var client = new SendGridClient(“APIKey”);
var from = new EmailAddress(“test@example.com”, “Example User”);
var subject = “Sending with SendGrid is Fun”;
var to = new EmailAddress(“test@example.com”, “Example User”);
var plainTextContent = “and easy to do anywhere, even with C#”;
var htmlContent = “<strong>and easy to do anywhere, even with C#</strong>”;
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
}
}
}

Now run this application on your side and click on verify on the SendGrid page.

The SendGrid site will display if your api key and your attempt to send the email was successful.

Once we have successfully tested our apiKey, now we can successfully integrate it into our .NET Core MVC application.

Integrating SendGrid in .NET Core MVC application, using templates and providing dynamic data

This part involves two tasks one on the SendGrid side and the other on our .Net application.

SendGrid Side:

Login to SendGrid and go to the dynamic-templates page and click on “Create a dynamic template

You can either opt for the design editor or code editor.

If you need help to choose which editor will best suit you, read this document.

Design your desired template.

Note the Template ID

Dynamically providing data to the template:

SendGrid email templates take dynamic data in JSON format. As you know, JSON works in key-value pairs, specify the key in the template.

For eg. if I want to dynamically specify the head to the template, I can write {{head}} in the template and then pass the data through the application in json format to the template.

Similarly, if we want to dynamically change the image in the template, we can specify the url to it

.NET Side:

Add the emailModel and add the following:

public class EmailModel
{
[Required]
public string From { get; set; }
[Required]
public string To { get; set; }
[JsonProperty(“subject”)]
public string Subject { get; set; }
[JsonProperty(“body”)]
public string Body { get; set; }
public string Title { get; set; }
[JsonProperty(“imageUrl0”)]
public string ImageUrl0 { get; set; }
[JsonProperty(“head”)]
public string Head { get; set; }
[JsonProperty(“imageUrl1”)]
public string ImageUrl1 { get; set; }
[JsonProperty(“bodyHead”)]
public string BodyHead { get; set; }
[JsonProperty(“buttonText”)]
public string ButtonText { get; set; }
[JsonProperty(“buttonLink”)]
public string ButtonLink { get; set; }
[JsonProperty(“imageUrl2”)]
public string ImageUrl2 { get; set; }
}

In the Controller add the following:

public async Task<ActionResult> PostMessage(EmailModel emailModel)
{
var apiKey = _configuration.GetSection(“SENDGRID_API_KEY”).Value;
var client = new SendGridClient(apiKey);
var sendGridMessage = new SendGridMessage();
sendGridMessage.SetFrom(emailModel.From);
sendGridMessage.AddTo(emailModel.To);
sendGridMessage.SetSubject(emailModel.Subject);
sendGridMessage.SetTemplateId(“TemplateID”);
sendGridMessage.SetTemplateData(emailModel);
//var displayRecipients = false; // set this to true if you want recipients to see each others mail id
var response = await client.SendEmailAsync(sendGridMessage);
// check if it is sent successfully and send report to client accordingly
if (response.IsSuccessStatusCode)
{
Console.WriteLine(“Email sent”);
return Ok();
}
return BadRequest();
}

You can now run and test your API using Postman/ If you are not making an apiController, You can make a suitable view for it and test it.

--

--

Praveen Korni
0 Followers

A software engineer, a poet. If you're reading a published article, he has probably taken huge amount of effort to resist his procrastination.