How to send emails using SendGrid in ASP.NET Core

By FoxLearn 12/31/2024 7:42:08 AM   191
In this article, we will walk through how to use SendGrid in an ASP.NET Core application to send emails.

We'll cover setting up your SendGrid account, configuring your application, and writing the necessary code to send emails using SendGrid’s API.

Why Use SendGrid?

SendGrid provides a powerful and easy-to-use API to integrate email functionality into your applications.

It offers a range of features, including:

  • Sending transactional and marketing emails.
  • Tracking email performance and delivery.
  • Optimizing email campaigns with templates and list management tools.
  • Additional services such as email validation and testing.

These features help ensure that emails are delivered efficiently while also allowing you to manage and monitor your email campaigns effectively.

Set Up Your SendGrid Account

To get started with SendGrid, follow these steps:

  1. Log in to your SendGrid account (or sign up if you don’t have one).
  2. Go to Settings > Sender Authentication.
  3. Select Single Sender Verification and click Get Started.
  4. Enter the sender details and click Verify Single Sender.
  5. Confirm your sender by clicking the verification email from SendGrid.
  6. Navigate to Settings > API Keys.
  7. Click Create API Key, specify the permission level, and click Create & View.
  8. Save the generated API key for future use.

Install the SendGrid NuGet Package

To use SendGrid in your ASP.NET Core project, you need to install the SendGrid NuGet package:

  • Open your project in Visual Studio.
  • Right-click on your project in Solution Explorer and choose "Manage NuGet Packages."
  • Search for "SendGrid" and install it.

Alternatively, you can install the package using the NuGet Package Manager Console:

PM> Install-Package SendGrid

Configure SendGrid in Your Application

In the application’s appsettings.json file, add your SendGrid API key and sender email information:

"EmailSettings": {
  "ApiKey": "your-sendgrid-api-key",
  "SenderEmail": "[email protected]",
  "SenderName": "Your Name"
}

Creating the EmailSettings class in C# to store the email configuration values such as API key, sender email, and sender name:

public class EmailSettings
{
    public string ApiKey { get; set; }
    public string SenderEmail { get; set; }
    public string SenderName { get; set; }
}

This class will be used to bind the values from your configuration file (e.g., appsettings.json) where you store the SendGrid API key and sender details.

In your Program.cs file, bind these settings to an EmailSettings class:

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

Create the EmailService Class

Next, you need to create an EmailService class that will handle sending emails. This service will use SendGrid’s API to send emails asynchronously.

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)
    {
        var fromEmail = _options.Value.SenderEmail;
        var fromName = _options.Value.SenderName;
        var apiKey = _options.Value.ApiKey;
        var client = 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);
        await client.SendEmailAsync(msg);
    }
}

Create the EmailController

Create an API controller, EmailController, that will receive requests to send emails.

[Route("api/[controller]")]
[ApiController]
public class EmailController : ControllerBase
{
    private readonly IEmailService _emailService;
    public EmailController(IEmailService emailService)
    {
        _emailService = emailService;
    }

    [HttpGet]
    public async Task<IActionResult> SendTestEmail()
    {
        await _emailService.SendEmailAsync("[email protected]", "Test Subject", "Test email body");
        return Ok();
    }
}

Register EmailService in Dependency Injection (DI)

Finally, register the EmailService in the DI container by adding the following line to Program.cs:

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

Instead of manually creating an EmailService, you can use SendGrid’s built-in integration by registering SendGrid as a service in Program.cs:

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

With these steps, you have successfully integrated SendGrid into your ASP.NET Core application.