How to Send Emails in ASP.NET Core

By FoxLearn 12/19/2024 2:51:14 PM   221
In this guide, we will learn how to send emails using ASP.NET Core.

We will start by creating a simple project and setting up a basic email configuration. Following the Single Responsibility Principle (SRP) from SOLID, we will design a dedicated email service.

send email in aspnet core

Add your email configuration to the appsettings.json file.

{
   "Logging": {
     "IncludeScopes": false,
     "Debug": {
       "LogLevel": {
          "Default": "Warning"
       }
     },
     "Console": {
       "LogLevel": {
         "Default": "Warning"
       }
     }
   },
    "Email": {
      "Email": "[email protected]",
      "Password": "password",
      "Host": "smtp.gmail.com",
      "Port": "587"
   }
}

This configuration will include details such as email, password, host, and port required for connecting to an SMTP server. Below is an example configuration:

To implement the Single Responsibility Principle, create a new folder named Services in your project.

Inside this folder, add an interface IEmailService and a class EmailService.

using System.Threading.Tasks;

namespace Email.Services
{
    public interface IEmailService
    {
        Task SendEmail(string email, string subject, string message);
    }
}

The EmailService class will handle the email-sending logic using the SmtpClient library.

using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace Email.Services
{
     public class EmailService : IEmailService
     {
          private readonly IConfiguration _configuration;

          public EmailService(IConfiguration configuration)
          {
               _configuration = configuration;
          }

          public async Task SendEmail(string email, string subject, string message)
          {
               using (var client = new SmtpClient())
               {
                   var credential = new NetworkCredential
                   {
                       UserName = _configuration["Email:Email"],
                       Password = _configuration["Email:Password"]
                   };

                   client.Credentials = credential;
                   client.Host = _configuration["Email:Host"];
                   client.Port = int.Parse(_configuration["Email:Port"]);
                   client.EnableSsl = true;

                   using (var emailMessage = new MailMessage())
                   {
                       emailMessage.To.Add(new MailAddress(email));
                       emailMessage.From = new MailAddress(_configuration["Email:Email"]);
                       emailMessage.Subject = subject;
                       emailMessage.Body = message;
                       client.Send(emailMessage);
                   }
               }
               await Task.CompletedTask;
          }
     }
}

The constructor takes an IConfiguration object to read email settings from appsettings.json.

The SendEmail method sets up the SMTP client and sends an email asynchronously.

All credentials and configurations are abstracted to ensure flexibility and security.

Modify the Account controller to inject the IEmailService and define an endpoint for sending emails.

private readonly IEmailService _emailService;

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

[HttpPost]
[Route("account/send-email")]
public async Task<IActionResult> SendEmailAsync(string email, string subject, string message)
{
    await _emailService.SendEmail(email, subject, message);
    return Ok();
}

Update the Startup.cs file to register the EmailService implementation for the IEmailService interface.

public void ConfigureServices(IServiceCollection services)
{
   //...
   services.AddTransient<IEmailService, EmailService>();
}

This ensures that whenever IEmailService is requested, an instance of EmailService will be provided.