How to send out emails utilizing SendGrid in ASP.NET Core

Uncategorized

You will often have the need to send e-mails through your application. There are several tools and libraries available to assist you achieve this. And cloud-based email services with friendly APIs make it simple to include rich email services into your applications. Among the most popular and useful cloud-based e-mail services is SendGrid.SendGrid can help organizations and designers send out both marketing and transactional e-mails. It provides an easy, reputable, and scalable email facilities that permits business to focus on their core operations while ensuring their e-mails are provided to the intended recipients. And SendGrid offers an API and libraries for several shows languages and frameworks including C# and.NET. In this short article, we’ll analyze how we can utilize SendGrid to send out 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 create a SendGrid API essential How to define SendGrid metadata in the application configuration file How to produce

  • the EmailService class to send e-mails utilizing SendGrid How to produce the EmailController class to accept HTTP requests To utilize the code examples
  • provided in this post, you need to have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022

    here. Likewise note that you will need to register for a SendGrid account to use the service. The totally free strategy enables you to send out 100 e-mails per day.Create an ASP.NET Core 7 Web API project in Visual Studio 2022 First off,

    let’s develop an ASP.NET Core 7 minimal Web API task in Visual Studio 2022. Follow these steps: Release the Visual Studio 2022 IDE. Click “Develop brand-new project.

    “In the “Produce brand-new job “window, select”ASP.NET Core

    Web API “from the list of design templates displayed. Click Next. In the “Configure your new project “window, define the name and area

  • for the brand-new job.
  • Optionally examine the”
  • Place solution and task in the same directory site”check box, depending upon your choices. Click Next.
  • In the “Additional
  • Info”window shown next, uncheck the check box that states “Usage 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,””Set up for HTTPS, “and” Enable Docker “are uncontrolled as we won’t be using those features here. Click Create. We’ll utilize this ASP.NET Core 7 Web API
  • task to deal with SendGrid in the sections below.Why usage SendGrid?SendGrid’s e-mail API makes it simple for developers to incorporate email performance into their applications. You can use the SendGrid API to send emails, track e-mail delivery, and monitor email efficiency. With SendGrid, businesses can easily send out automatic email messages, including welcome emails, password reset notices, delivering confirmations, purchase invoices, and more. SendGrid’s platform offers a variety of features developed to make sending e-mails more uncomplicated and effective.SendGrid likewise uses tools that assist businesses
  • design, manage, and optimize e-mail projects.

    These tools include e-mail templates, list management functions, and campaign analytics. In addition to its core e-mail services, SendGrid provides a variety of add-on services consisting of e-mail validation, confirmation, and screening tools.Generate an API type in SendGrid If you currently 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: Visit to your SendGrid account. Select Settings -> Sender Authentication. Select”Single Sender Verification. “Click the “Start”button. Develop a Sender by defining the sender details. Click on the”Validate Single Sender”button. Verify your single sender by clicking

    the e-mail you receive from SendGrid. Next, select Settings- > API Keys. Click the”Create API Secret”button. Specify the authorization level for your API secret. Click the”Develop & View”button to produce the API key. Save the produced API secret since you’ll be utilizing it soon

  • . Install the SendGrid NuGet bundle So far so good. Now
  • include the SendGrid NuGet package to your project in
  • Visual Studio. To do this, pick the job
  • in the Option Explorer window and right-click and select”Manage NuGet Plans. “In the NuGet Package Manager window, search for the SendGrid package and install it. Alternatively, you can set up the bundle by means of the NuGet Bundle Manager console by entering the line shown below.PM > Install-Package SendGrid Specify SendGrid metadata in the setup file Produce a section called EmailSettings in your application’s configuration file and go into the following
  • code therein.”EmailSettings “: Make certain to replace”Specify your SendGrid API Secret “with your SendGrid API secret for the SendGrid account you’re using.To bind a circumstances of type EmailSettings to the setup worths, get in the following code in the Program.cs

    file. builder.Services.Configure (options=> builder.Configuration.GetSection (“EmailSettings”). Bind( alternatives)); Utilizing SendGrid in ASP.NET Core In this section, we’ll take a look at how we can send out email utilizing SendGrid in ASP.NET

  • Core.Create the EmailService Class Now, develop a class named EmailService that will be responsible for sending emails using SendGrid. To do this, produce a new.cs submit called EmailService.cs and enter the following code.public class EmailService: IEmailService private readonly IConfiguration _ configuration; personal readonly IOptions _ alternatives; public EmailService(IConfiguration setup, IOptions choices)p>

    _ setup=setup; _ choices=alternatives; public async Job SendEmailAsync(string e-mail, string topic, string htmlMessage)string? fromEmail =_ options.Value.SenderEmail; string? fromName=_ options.Value.SenderName; string? apiKey=_ options.Value.ApiKey

    ; var sendGridClient=brand-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 reaction=await sendGridClient.SendEmailAsync(msg); Keep in mind how the Options pattern has been used here to obtain the email metadata from the application setup file.Create the EmailController class Develop a brand-new API controller in your job called EmailController. In your controller, inject a circumstances of type EmailService and call the SendEmailAsync approach: [Path (“api/ [controller])] [ApiController]. public class EmailController: ControllerBase. personal readonly IEmailService _ emailService; private readonly ILogger _ logger; public EmailController(IEmailService emailService, ILogger logger)_ emailService=emailService; _ logger = logger; [. HttpGet] public async Task Get() await _ emailService.SendEmailAsync(” [email protected]”,”Some subject”, “Define the html material here”); return Ok();. Now include a Singleton service of type IEmailService by consisting of the following code in

    the Program.cs file.builder.Services.AddSingleton( ); That’s it! When you run your application and execute the HttpGet action of your EmailController,

    an e-mail will be sent out using the SendGrid library.Register SendGrid as a service and utilize DI Note that you can likewise register SendGrid as a service and benefit from reliance injection to inject an instance of SendGrid in your application. To sign up SendGrid as a service, go into the following code in the Program.cs file.using SendGrid.Extensions.DependencyInjection; builder.Services.AddSendGrid(alternatives= > ); As we have actually seen, SendGrid provides a robust API that we can use to quickly incorporate its e-mail capabilities into our applications. SendGrid also incorporates with various third-party applications and services consisting of WordPress, Salesforce, Shopify, and Microsoft Azure. If you require a reliable and scalable email service to assist you reach your audience and grow your service, SendGrid is a fantastic choice. Copyright ©

    2023 IDG Communications, Inc. Source

  • Leave a Reply

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