You’ll usually have the necessity to ship emails by your software. There are a number of instruments and libraries out there that will help you obtain this. And cloud-based e mail companies with pleasant APIs make it straightforward to include wealthy e mail companies into your functions. Probably the most standard and helpful cloud-based e mail companies is SendGrid.
SendGrid may also help companies and builders ship each advertising and marketing and transactional emails. It supplies a easy, dependable, and scalable e mail infrastructure that permits firms to concentrate on their core operations whereas making certain their emails are delivered to the meant recipients. And SendGrid supplies an API and libraries for a lot of completely different programming languages and frameworks together with C# and .NET.
On this article, we’ll look at how we will use SendGrid to ship emails from an ASP.NET Core 7 software. We’ll cowl the next factors:
- An introduction to SendGrid and why it’s helpful
- Find out how to generate a SendGrid API key
- Find out how to specify SendGrid metadata within the software configuration file
- Find out how to create the EmailService class to ship emails utilizing SendGrid
- Find out how to create the EmailController class to simply accept HTTP requests
To make use of the code examples offered on this article, it’s best to have Visible Studio 2022 put in in your system. In case you don’t have already got a replica, you may obtain Visible Studio 2022 right here.
Additionally word that you will want to join a SendGrid account to make use of the service. The free plan lets you ship 100 emails per day.
Create an ASP.NET Core 7 Net API venture in Visible Studio 2022
First off, let’s create an ASP.NET Core 7 minimal Net API venture in Visible Studio 2022. Comply with these steps:
- Launch the Visible Studio 2022 IDE.
- Click on on “Create new venture.”
- Within the “Create new venture” window, choose “ASP.NET Core Net API” from the checklist of templates displayed.
- Click on Subsequent.
- Within the “Configure your new venture” window, specify the title and site for the brand new venture.
- Optionally examine the “Place answer and venture in the identical listing” examine field, relying in your preferences.
- Click on Subsequent.
- Within the “Extra Info” window proven subsequent, uncheck the examine field that claims “Use controllers…” as we’ll be utilizing minimal APIs on this instance. Go away the “Authentication Sort” as “None” (default).
- Be certain that the examine containers “Allow Open API Assist,” “Configure for HTTPS,” and “Allow Docker” are unchecked as we gained’t be utilizing these options right here.
- Click on Create.
We’ll use this ASP.NET Core 7 Net API venture to work with SendGrid within the sections under.
Why use SendGrid?
SendGrid’s e mail API makes it straightforward for builders to combine e mail performance into their functions. You should use the SendGrid API to ship emails, monitor e mail supply, and monitor e mail efficiency.
With SendGrid, companies can simply ship automated e mail messages, together with welcome emails, password reset notifications, delivery confirmations, buy receipts, and extra. SendGrid’s platform gives a wide range of options designed to make sending emails extra easy and efficient.
SendGrid additionally gives instruments that assist companies design, handle, and optimize e mail campaigns. These instruments embrace e mail templates, checklist administration options, and marketing campaign analytics. Along with its core e mail companies, SendGrid gives a variety of add-on companies together with e mail validation, verification, and testing instruments.
Generate an API key in SendGrid
If you have already got a SendGrid account, you may login and proceed from there. If not, you may join a brand new SendGrid account right here. Then comply with these steps:
- Log in to your SendGrid account.
- Choose Settings -> Sender Authentication.
- Choose “Single Sender Verification.”
- Click on on the “Get Began” button.
- Create a Sender by specifying the sender particulars.
- Click on on the “Confirm Single Sender” button.
- Confirm your single sender by clicking on the e-mail you obtain from SendGrid.
- Subsequent, choose Settings -> API Keys.
- Click on on the “Create API Key” button.
- Specify the permission degree on your API key.
- Click on on the “Create & View” button to generate the API key.
- Save the generated API key since you’ll be utilizing it shortly.
Set up the SendGrid NuGet bundle
Up to now so good. Now add the SendGrid NuGet bundle to your venture in Visible Studio. To do that, choose the venture within the Answer Explorer window and right-click and choose “Handle NuGet Packages.” Within the NuGet Bundle Supervisor window, seek for the SendGrid bundle and set up it.
Alternatively, you may set up the bundle through the NuGet Bundle Supervisor console by getting into the road proven under.
PM> Set up-Bundle SendGrid
Specify SendGrid metadata within the configuration file
Create a bit named EmailSettings in your software’s configuration file and enter the next code in there.
"EmailSettings": { "ApiKey": "Specify your Api Key right here...", "SenderEmail": "testaddress@testemail.com", "SenderName": "NoReply" }
Make sure that to switch “Specify your SendGrid API Key” together with your SendGrid API key for the SendGrid account you’re utilizing.
To bind an occasion of sort EmailSettings to the configuration values, enter the next code within the Program.cs file.
builder.Companies.Configure<EmailSettings> (choices => builder.Configuration.GetSection("EmailSettings").Bind(choices));
Utilizing SendGrid in ASP.NET Core
On this part, we’ll look at how we will ship e mail utilizing SendGrid in ASP.NET Core.
Create the EmailService Class
Now, create a category named EmailService that will likely be answerable for sending emails utilizing SendGrid. To do that, create a brand new .cs file named EmailService.cs and enter the next code.
public class EmailService : IEmailService { non-public readonly IConfiguration _configuration; non-public readonly IOptions<EmailSettings> _options; public EmailService(IConfiguration configuration, IOptions<EmailSettings> choices) { _configuration = configuration; _options = choices; } public async Job SendEmailAsync(string e mail, string topic, string htmlMessage) { string? fromEmail = _options.Worth.SenderEmail; string? fromName = _options.Worth.SenderName; string? apiKey = _options.Worth.ApiKey; var sendGridClient = new SendGridClient(apiKey); var from = new EmailAddress(fromEmail, fromName); var to = new EmailAddress(e mail); var plainTextContent = Regex.Substitute(htmlMessage, "<[^>]*>", ""); var msg = MailHelper.CreateSingleEmail(from, to, topic, plainTextContent, htmlMessage); var response = await sendGridClient.SendEmailAsync(msg); } }
Be aware how the Choices sample has been used right here to retrieve the e-mail metadata from the applying configuration file.
Create the EmailController class
Create a brand new API controller in your venture named EmailController. In your controller, inject an occasion of sort EmailService and name the SendEmailAsync methodology:
[Route("api/[controller]")] [ApiController] public class EmailController : ControllerBase { non-public readonly IEmailService _emailService; non-public readonly ILogger<EmailController> _logger; public EmailController(IEmailService emailService, ILogger<EmailController> logger) { _emailService = emailService; _logger = logger; } [HttpGet] public async Job<IActionResult> Get() { await _emailService.SendEmailAsync("e mail@e mail.com", "Some topic", "Specify the html content material right here"); return Okay(); } }
Now add a Singleton service of sort IEmailService by together with the next code within the Program.cs file.
builder.Companies.AddSingleton<IEmailService, EmailService>();
That’s it! If you run your software and execute the HttpGet motion of your EmailController, an e mail will likely be despatched utilizing the SendGrid library.
Register SendGrid as a service and use DI
Be aware that you would be able to additionally register SendGrid as a service and benefit from dependency injection to inject an occasion of SendGrid in your software. To register SendGrid as a service, enter the next code within the Program.cs file.
utilizing SendGrid.Extensions.DependencyInjection; builder.Companies.AddSendGrid(choices => { choices.ApiKey = builder.Configuration .GetSection("EmailSettings").GetValue<string>("ApiKey"); });
As we’ve seen, SendGrid gives a strong API that we will use to simply combine its e mail capabilities into our functions. SendGrid additionally integrates with numerous third-party functions and companies together with WordPress, Salesforce, Shopify, and Microsoft Azure. In case you want a dependable and scalable e mail service that will help you attain your viewers and develop your enterprise, SendGrid is a superb selection.
Copyright © 2023 IDG Communications, Inc.