Take advantage of SendGrid to integrate reliable and scalable email into your ASP.NET Core applications. Here’s how. Credit: 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: Launch the Visual Studio 2022 IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences. Click Next. 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). 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. 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: Log in to your SendGrid account. Select Settings -> Sender Authentication. Select “Single Sender Verification.” Click on the “Get Started” button. Create a Sender by specifying the sender details. Click on the “Verify Single Sender” button. Verify your single sender by clicking on the email you receive from SendGrid. Next, select Settings -> API Keys. Click on the “Create API Key” button. Specify the permission level for your API key. Click on the “Create & View” button to generate the API key. 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. Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos