Press "Enter" to skip to content

How to send emails using SendGrid in ASP.NET Core

You will often have a 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 embed 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 transactional and marketing emails. It provides a simple, reliable, and scalable email infrastructure that allows businesses to focus on their core operations while ensuring their emails are delivered to their intended recipients. And SendGrid provides an API and libraries for many different programming languages ​​and frameworks, including C# and .NET.

In this article, we will examine how we can use SendGrid to send email from an ASP.NET Core 7 application. We will 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 EmailService class to send emails using SendGrid
  • How to create the EmailController class to accept HTTP requests

To use the code samples provided in this article, you must have Visual Studio 2022 installed on 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, let’s create a minimal ASP.NET Core 7 Web API project in Visual Studio 2022. Follow these steps:

  1. Start the Visual Studio 2022 IDE.
  2. Click “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 “Set up your new project” window, specify the name and location of the new project.
  6. Optionally, check the “Place solution and project in the same directory” checkbox, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown below, uncheck the checkbox that says “Use Controllers…” as we will be using minimal APIs in this example. Leave the “Authentication Type” as “None” (default).
  9. Make sure the “Enable Open API Support”, “Configure for HTTPS” and “Enable Docker” checkboxes are not checked, 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 email, 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. The SendGrid platform offers a variety of features designed to make sending email easier and more 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 log in and continue from there. If not, you can sign up for a new SendGrid account here. Then follow these steps:

  1. Sign in to your SendGrid account.
  2. Select Settings -> Sender Authentication.
  3. Select “Single Sender Verification”.
  4. Click the “Get Started” button.
  5. Create a sender by specifying the sender details.
  6. Click the “Verify Single Sender” button.
  7. Verify your unique sender by clicking on the email you receive from SendGrid.
  8. Then select Settings -> API Keys.
  9. Click the “Create API Key” button.
  10. Specify the permission level for your API key.
  11. Click the “Create and View” button to generate the API key.
  12. Save the generated API key as you will be using it shortly.
Also Read:  How to handle errors in minimal APIs in ASP.NET Core

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, find the SendGrid package and install it.

Alternatively, you can install the package through 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 called Email Settings in your application’s configuration file and enter the following code there.

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

Be sure to replace “Specify your SendGrid API Key” with your SendGrid API Key for the SendGrid account you are using.

To bind an instance of type EmailSettings to configuration settings, 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 look at how we can send email using SendGrid in ASP.NET Core.

Create the email service class

Now, create a class called EmailService that will be responsible for sending emails using SendGrid. To do this, create a new .cs file called 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);
   }
}

Notice 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 called 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 all! When you run your application and call 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 into 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 apps 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.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *