Send Email Using ASP.NET Core 5 Web API

Introduction

Sending emails using ASP.NET Core 5 Web API can be accomplished using the built-in SmtpClient class or external libraries like SendGrid. Below, I’ll provide an example using SmtpClient to send emails via SMTP:

  1. Create a New ASP.NET Core Web API Project:
    Use the following command to create a new ASP.NET Core Web API project:
   dotnet new webapi -n EmailSenderDemo
   cd EmailSenderDemo
  1. Configure SMTP Settings:
    In your appsettings.json file, add the SMTP settings:
   {
     "SmtpSettings": {
       "Host": "your-smtp-host",
       "Port": 587,
       "Username": "your-username",
       "Password": "your-password",
       "SenderEmail": "sender@example.com",
       "SenderName": "Your Sender Name"
     },
     // Other settings
   }

Replace the placeholders with your actual SMTP server details.

  1. Install NuGet Packages:
    Install the necessary NuGet package for sending emails via SMTP:
   dotnet add package System.Net.Mail
  1. Create an Email Service:
    Create an email service class that encapsulates the email sending logic. You can create a new class called EmailService.cs:
   using Microsoft.Extensions.Configuration;
   using System.Net;
   using System.Net.Mail;
   using System.Threading.Tasks;

   public class EmailService : IEmailService
   {
       private readonly SmtpSettings _smtpSettings;

       public EmailService(IConfiguration configuration)
       {
           _smtpSettings = configuration.GetSection("SmtpSettings").Get<SmtpSettings>();
       }

       public async Task SendEmailAsync(string toEmail, string subject, string body)
       {
           using (var client = new SmtpClient(_smtpSettings.Host, _smtpSettings.Port))
           {
               client.UseDefaultCredentials = false;
               client.Credentials = new NetworkCredential(_smtpSettings.Username, _smtpSettings.Password);
               client.EnableSsl = true;

               var message = new MailMessage
               {
                   From = new MailAddress(_smtpSettings.SenderEmail, _smtpSettings.SenderName),
                   Subject = subject,
                   Body = body,
                   IsBodyHtml = true
               };
               message.To.Add(new MailAddress(toEmail));

               await client.SendMailAsync(message);
           }
       }
   }
  1. Create a DTO for SMTP Settings:
    Create a DTO (Data Transfer Object) class to hold SMTP settings:
   public class SmtpSettings
   {
       public string Host { get; set; }
       public int Port { get; set; }
       public string Username { get; set; }
       public string Password { get; set; }
       public string SenderEmail { get; set; }
       public string SenderName { get; set; }
   }
  1. Inject the Email Service:
    Register the email service in the Startup.cs file:
   services.AddSingleton<IEmailService, EmailService>();
  1. Create a Controller:
    Create a controller to send emails. You can create a new controller called EmailController.cs:
   using Microsoft.AspNetCore.Mvc;
   using System.Threading.Tasks;

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

       public EmailController(IEmailService emailService)
       {
           _emailService = emailService;
       }

       [HttpPost]
       public async Task<IActionResult> SendEmail([FromBody] EmailRequest request)
       {
           await _emailService.SendEmailAsync(request.ToEmail, request.Subject, request.Body);
           return Ok("Email sent successfully");
       }
   }
  1. Run the Application:
    Start the application using the following command:
   dotnet run

You can use tools like curl, Postman, or a browser to send POST requests to the /api/email endpoint with the appropriate JSON payload, such as:

   {
       "toEmail": "recipient@example.com",
       "subject": "Test Email",
       "body": "<h1>Hello, this is a test email.</h1>"
   }

This example demonstrates how to send emails using the SmtpClient class in an ASP.NET Core 5 Web API. Remember that for production use, it’s important to handle exceptions and errors, and consider using more advanced email libraries or services like SendGrid for enhanced features and deliverability.

Leave a Reply

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