Sunday, May 28, 2023

Easy methods to ship emails utilizing SendGrid in ASP.NET Core

Latest News

I usually must ship emails by way of an software. There are a number of instruments and libraries obtainable to perform this. As well as, cloud-based e mail companies with easy-to-use APIs make it simple to include wealthy e mail companies into your functions. One of the crucial widespread and handy cloud-based e mail companies is SendGrid.

SendGrid helps companies and builders ship each advertising and marketing and transactional emails. By offering a easy, dependable, and scalable e mail infrastructure, companies can concentrate on their core operations whereas making certain e mail is delivered to the meant recipients. SendGrid additionally supplies APIs and libraries for numerous programming languages ​​and frameworks, together with C# and .NET.

This text demonstrates use SendGrid to ship emails from an ASP.NET Core 7 software. We are going to cowl the next factors:

  • An summary of SendGrid and its usefulness
  • Easy methods to generate a SendGrid API key
  • Easy methods to specify SendGrid metadata in your software configuration file
  • Easy methods to create an EmailService class for sending emails utilizing SendGrid
  • Easy methods to create an EmailController class that accepts HTTP requests

To make use of the code examples supplied on this article, it’s essential to have Visible Studio 2022 put in in your system. In the event you do not have already got a duplicate, you may obtain Visible Studio 2022 right here.

Additionally notice that it’s essential to join a SendGrid account to make use of the service. The free plan permits you to ship 100 emails per day.

Create an ASP.NET Core 7 Net API venture in Visible Studio 2022

Let’s begin by making a minimal ASP.NET Core 7 Net API venture in Visible Studio 2022. Comply with these steps:

  1. Begin the Visible Studio 2022 IDE.
  2. Click on Create new venture.
  3. Within the Create New Venture window, choose ASP.NET Core Net API from the record of templates displayed.
  4. Click on (Subsequent).
  5. Within the (Configure your new venture) window, specify a reputation and site on your new venture.
  6. Choose the (Place resolution and venture in similar listing) verify field if desired.
  7. Click on (Subsequent).
  8. Within the (Further Data) window that seems subsequent, uncheck the field that claims (Use controllers…). It’s because this instance makes use of a minimal API. Go away Authentication Sort as None (default).
  9. Be certain that the (Allow Open API Help), (Configure for HTTPS), and (Allow Docker) checkboxes are cleared, as we won’t be utilizing these options right here.
  10. Click on (Create).
See also  Why Microsoft Integrates All Its Knowledge Analytics Merchandise Into Cloth

Within the following sections, we’ll use this ASP.NET Core 7 Net API venture to work with SendGrid.

Why SendGrid?

SendGrid’s e mail API makes it simple for builders to combine e mail performance into their functions. You should use the SendGrid API to ship emails, observe e mail supply, and monitor e mail efficiency.

SendGrid makes it simple to ship automated e mail messages, together with welcome emails, password reset notifications, delivery confirmations, buy receipts, and extra. SendGrid’s platform provides a wide range of options designed to make sending emails simpler and more practical.

SendGrid additionally provides instruments to assist companies design, handle, and optimize their e mail campaigns. These instruments embrace e mail templates, record administration options, and marketing campaign analytics. Along with our core e mail service, SendGrid provides a wide range of add-on companies equivalent to e mail verification, validation, and testing instruments.

Generate an API Key with SendGrid

If you have already got a SendGrid account, you may log in and proceed from there. If not, you may join a brand new SendGrid account right here. Then observe these steps:

  1. Log in to your SendGrid account.
  2. Choose (Settings)->(Sender Authentication).
  3. Choose Single Sender Verification.
  4. Click on the “Get Began” button.
  5. Create a sender by specifying the sender particulars.
  6. Click on the Verify Single Sender button.
  7. Click on on an e mail obtained from SendGrid to confirm a single sender.
  8. Then choose (Settings) -> (API Keys).
  9. Click on the Create API Key button.
  10. Specifies the permission stage of the API key.
  11. Click on the (Create & View) button to generate an API key.
  12. Save the generated API key as you’ll use it quickly.
See also  Unhealthy week for Docker

Set up the SendGrid NuGet package deal

To this point, so good. Now add the SendGrid NuGet package deal to your venture in Visible Studio. To do that, choose the venture within the Resolution Explorer window, right-click and choose (Handle NuGet Packages). Within the (NuGet Bundle Supervisor) window, seek for the SendGrid package deal and set up it.

Alternatively, you may set up the package deal from the NuGet Bundle Supervisor Console by typing the road proven beneath.

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 it.

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

Change “Specify your SendGrid API Key” with the SendGrid API key on your SendGrid account.

To bind an occasion of kind EmailSettings to a configuration worth, enter the next code in your Program.cs file.

builder.Companies.Configure<EmailSettings>
   (choices => builder.Configuration.GetSection("EmailSettings").Bind(choices));

Utilizing SendGrid with ASP.NET Core

This part describes ship e mail utilizing SendGrid in ASP.NET Core.

Create the EmailService class

Now create a category named EmailService that might 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 Activity 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.Change(htmlMessage, "<(^>)*>", "");
       var msg = MailHelper.CreateSingleEmail(from, to, topic,
       plainTextContent, htmlMessage);
       var response = await sendGridClient.SendEmailAsync(msg);
   }
}

Notice how the choice sample is used right here to retrieve the e-mail metadata from the appliance configuration file.

See also  Codebase GitGuardian's Honeytokens for Looking DevOps Intrusions

Create an EmailController class

Create a brand new API controller named EmailController in your venture. In your controller, inject an occasion of kind 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 Activity<IActionResult> Get()
   {
       await _emailService.SendEmailAsync("e mail@e mail.com", "Some topic", "Specify the html content material right here");
       return Okay();
   }
}

Then add a Singleton service of kind IEmailService by together with the next code in your Program.cs file:

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

that is it! Once I run the appliance and execute his HttpGet motion in EmailController, the e-mail is shipped utilizing the SendGrid library.

Register SendGrid as a service and use DI

You can even register SendGrid as a service and use dependency injection to inject an occasion of SendGrid into your software. To register SendGrid as a service, enter the next code in your Program.cs file.

utilizing SendGrid.Extensions.DependencyInjection;
builder.Companies.AddSendGrid(choices =>
{
    choices.ApiKey = builder.Configuration
    .GetSection("EmailSettings").GetValue<string>("ApiKey");
});

As you’ve got seen, SendGrid supplies a sturdy API that you should use to simply combine e mail performance into your functions. SendGrid additionally integrates with numerous third-party functions and companies equivalent to WordPress, Salesforce, Shopify, Microsoft Azure, and extra. In the event you want a dependable, scalable e mail service to succeed in your viewers and develop what you are promoting, SendGrid is for you.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Hot Topics

Related Articles