How to send emails using SendGrid in ASP.NET Core

Take advantage of SendGrid to integrate reliable and scalable email into your ASP.NET Core applications. Here’s how.

email image blue
Molnia/iStock

You will often have the need to send emails through your application. There are several tools and libraries available to help you achieve this. And cloud-based email services with friendly APIs make it easy to incorporate rich email services into your applications. One of the most popular and useful cloud-based email services is SendGrid.

SendGrid can help businesses and developers send both marketing and transactional emails. It provides a simple, reliable, and scalable email infrastructure that allows companies to focus on their core operations while ensuring their emails are delivered to the intended recipients. And SendGrid provides an API and libraries for many different programming languages and frameworks including C# and .NET

In this article, we’ll examine how we can use SendGrid to send emails from an ASP.NET Core 7 application. We’ll cover the following points:

  • An introduction to SendGrid and why it is useful
  • How to generate a SendGrid API key
  • How to specify SendGrid metadata in the application configuration file
  • How to create the EmailService class to send emails using SendGrid
  • How to create the EmailController class to accept HTTP requests

To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Also note that you will need to sign up for a SendGrid account to use the service. The free plan allows you to send 100 emails per day.

Create an ASP.NET Core 7 Web API project in Visual Studio 2022

First off, let’s create an ASP.NET Core 7 minimal Web API project in Visual Studio 2022. Follow these steps:

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, uncheck the check box that says “Use controllers…” as we’ll be using minimal APIs in this example. Leave the “Authentication Type” as “None” (default).
  9. Ensure that the check boxes “Enable Open API Support,” “Configure for HTTPS,” and “Enable Docker” are unchecked as we won’t be using those features here.
  10. Click Create.

We’ll use this ASP.NET Core 7 Web API project to work with SendGrid in the sections below.

Why use SendGrid?

SendGrid’s email API makes it easy for developers to integrate email functionality into their applications. You can use the SendGrid API to send emails, track email delivery, and monitor email performance.

With SendGrid, businesses can easily send automated email messages, including welcome emails, password reset notifications, shipping confirmations, purchase receipts, and more. SendGrid’s platform offers a variety of features designed to make sending emails more effortless and effective.

SendGrid also offers tools that help businesses design, manage, and optimize email campaigns. These tools include email templates, list management features, and campaign analytics. In addition to its core email services, SendGrid offers a range of add-on services including email validation, verification, and testing tools.

Generate an API key in SendGrid

If you already have a SendGrid account, you can login and proceed from there. If not, you can sign up for a new SendGrid account here. Then follow these steps:

  1. Log in to your SendGrid account.
  2. Select Settings -> Sender Authentication.
  3. Select “Single Sender Verification.”
  4. Click on the “Get Started” button.
  5. Create a Sender by specifying the sender details.
  6. Click on the “Verify Single Sender” button.
  7. Verify your single sender by clicking on the email you receive from SendGrid.
  8. Next, select Settings -> API Keys.
  9. Click on the “Create API Key” button.
  10. Specify the permission level for your API key.
  11. Click on the “Create & View” button to generate the API key.
  12. Save the generated API key because you’ll be using it shortly.

Install the SendGrid NuGet package

So far so good. Now add the SendGrid NuGet package to your project in Visual Studio. To do this, select the project in the Solution Explorer window and right-click and select “Manage NuGet Packages.” In the NuGet Package Manager window, search for the SendGrid package and install it.

Alternatively, you can install the package via the NuGet Package Manager console by entering the line shown below.

PM> Install-Package SendGrid

Specify SendGrid metadata in the configuration file

Create a section named EmailSettings in your application’s configuration file and enter the following code in there.

  "EmailSettings": {
    "ApiKey": "Specify your Api Key here...",
    "SenderEmail": "testaddress@testemail.com",
    "SenderName": "NoReply"
  }

Make sure to replace "Specify your SendGrid API Key" with your SendGrid API key for the SendGrid account you’re using.

To bind an instance of type EmailSettings to the configuration values, enter the following code in the Program.cs file.

builder.Services.Configure<EmailSettings>
   (options => builder.Configuration.GetSection("EmailSettings").Bind(options));

Using SendGrid in ASP.NET Core

In this section, we’ll examine how we can send email using SendGrid in ASP.NET Core.

Create the EmailService Class

Now, create a class named EmailService that will be responsible for sending emails using SendGrid. To do this, create a new .cs file named EmailService.cs and enter the following code.

public class EmailService : IEmailService
{
    private readonly IConfiguration _configuration;
    private readonly IOptions<EmailSettings>  _options;
    public EmailService(IConfiguration configuration, IOptions<EmailSettings> options)
    {
         _configuration = configuration;
         _options = options;
    }
public async Task SendEmailAsync(string email, string subject, string htmlMessage)
  {
       string? fromEmail = _options.Value.SenderEmail;
       string? fromName = _options.Value.SenderName;
       string? apiKey = _options.Value.ApiKey;
       var sendGridClient = new SendGridClient(apiKey);
       var from = new EmailAddress(fromEmail, fromName);
       var to = new EmailAddress(email);
       var plainTextContent = Regex.Replace(htmlMessage, "<[^>]*>", "");
       var msg = MailHelper.CreateSingleEmail(from, to, subject,
       plainTextContent, htmlMessage);
       var response = await sendGridClient.SendEmailAsync(msg);
   }
}

Note how the Options pattern has been used here to retrieve the email metadata from the application configuration file.

Create the EmailController class

Create a new API controller in your project named EmailController. In your controller, inject an instance of type EmailService and call the SendEmailAsync method:

[Route("api/[controller]")]
[ApiController]
public class EmailController : ControllerBase
{
   private readonly IEmailService _emailService;
   private readonly ILogger<EmailController> _logger;
   public EmailController(IEmailService emailService,
        ILogger<EmailController> logger)
   {
            _emailService = emailService;
            _logger = logger;
   }
   [HttpGet]
   public async Task<IActionResult> Get()
   {
       await _emailService.SendEmailAsync("email@email.com", "Some subject", "Specify the html content here");
       return Ok();
   }
}

Now add a Singleton service of type IEmailService by including the following code in the Program.cs file.

builder.Services.AddSingleton<IEmailService, EmailService>();

That’s it! When you run your application and execute the HttpGet action of your EmailController, an email will be sent using the SendGrid library.

Register SendGrid as a service and use DI

Note that you can also register SendGrid as a service and take advantage of dependency injection to inject an instance of SendGrid in your application. To register SendGrid as a service, enter the following code in the Program.cs file.

using SendGrid.Extensions.DependencyInjection;
builder.Services.AddSendGrid(options =>
{
    options.ApiKey = builder.Configuration
    .GetSection("EmailSettings").GetValue<string>("ApiKey");
});

As we’ve seen, SendGrid offers a robust API that we can use to easily integrate its email capabilities into our applications. SendGrid also integrates with various third-party applications and services including WordPress, Salesforce, Shopify, and Microsoft Azure. If you need a reliable and scalable email service to help you reach your audience and grow your business, SendGrid is a great choice.

Copyright © 2023 IDG Communications, Inc.

How to choose a low-code development platform