In this article, we will learn how to send an email in ASP.Net Core Web API. We will code the endpoint that will send the email to a user of your business customers. I am implementing the Cloud Native Microservices architecture in my project. And this service is one of the microservices of my project and I will extend this Microservice to handle all types of emails in my project.
Create the ASP.Net Core Web API Project
First, you need to create the ASP.Net core web project using the ASP.Net core 5 web API.
Install the MailKit Nuget Package
Right click on your Solution File. Now click on select the option Nuget Package and then find the MailKit Library for your project configuration. After the installation of this library, add the reference in the code.
Install-Package NETCore.MailKit
C#
You need to include the following namespaces in your code for the correct configuration.
using MailKit.Net.Smtp;
using MailKit.Security;
Add the Folder Model
After the creation of the Model, now create the class MailRequest with the following information.
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace _101SendEmailNotificationDoNetCoreWebAPI.Model
{
public class MailRequest
{
public string ToEmail { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public List<IFormFile> Attachments { get; set; }
}
}
Not Add the Folder Services
After the creation of the folder now add the following classes.
IMailService
using _101SendEmailNotificationDoNetCoreWebAPI.Model;
using System.Threading.Tasks;
namespace _101SendEmailNotificationDoNetCoreWebAPI.Services
{
public interface IMailService
{
Task SendEmailAsync(MailRequest mailRequest);
}
}
using MimeKit;
using System.IO;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
using _101SendEmailNotificationDoNetCoreWebAPI.Settings;
using _101SendEmailNotificationDoNetCoreWebAPI.Model;
namespace _101SendEmailNotificationDoNetCoreWebAPI.Services
{
public class MailService : IMailService
{
private readonly MailSettings _mailSettings;
public MailService(IOptions<MailSettings> mailSettings)
{
_mailSettings = mailSettings.Value;
}
public async Task SendEmailAsync(MailRequest mailRequest)
{
var email = new MimeMessage();
email.Sender = MailboxAddress.Parse(_mailSettings.Mail);
email.To.Add(MailboxAddress.Parse(mailRequest.ToEmail));
email.Subject = mailRequest.Subject;
var builder = new BodyBuilder();
if (mailRequest.Attachments != null)
{
byte[] fileBytes;
foreach (var file in mailRequest.Attachments)
{
if (file.Length > 0)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
fileBytes = ms.ToArray();
}
builder.Attachments.Add(file.FileName, fileBytes, ContentType.Parse(file.ContentType));
}
}
}
builder.HtmlBody = mailRequest.Body;
email.Body = builder.ToMessageBody();
using var smtp = new SmtpClient();
smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls);
smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password);
await smtp.SendAsync(email);
smtp.Disconnect(true);
}
}
}
Add the Folder Settings
Add the class setting in which you define the following Properties.
namespace _101SendEmailNotificationDoNetCoreWebAPI.Settings
{
public class MailSettings
{
public string Mail { get; set; }
public string DisplayName { get; set; }
public string Password { get; set; }
public string Host { get; set; }
public int Port { get; set; }
}
}
Add the Controller in the project
Create the Email Controller in which you define the endpoint. Send Email is responsible for sending the email to your business customers.
using _101SendEmailNotificationDoNetCoreWebAPI.Model;
using _101SendEmailNotificationDoNetCoreWebAPI.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace _101SendEmailNotificationDoNetCoreWebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class EmailController : Controller
{
private readonly IMailService mailService;
public EmailController(IMailService mailService)
{
this.mailService = mailService;
}
[HttpPost("Send")]
public async Task<IActionResult> Send([FromForm] MailRequest request)
{
try
{
await mailService.SendEmailAsync(request);
return Ok();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Configure Each Service In Start-up Class
using _101SendEmailNotificationDoNetCoreWebAPI.Services;
using _101SendEmailNotificationDoNetCoreWebAPI.Settings;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace _101SendEmailNotificationDoNetCoreWebAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MailSettings>(Configuration.GetSection("MailSettings"));
services.AddTransient<IMailService, Services.MailService>();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "_101SendEmailNotificationDoNetCoreWebAPI", Version = "v1" });
});
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "_101SendEmailNotificationDoNetCoreWebAPI v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Configure the Mail Setting in AppSetting.Json
Configure the SMTP Setting in AppSetting.Json in the following way,
"MailSettings": {
"Mail": "[email protected]",
"DisplayName": "Your Brand Name",
"Password": "YourPassword",
"Host": "SMTP Host",
"Port": 587
},
- Mail Define your email Address
- Display Name is your Brand Name
- The password of your SMTP Server
- The host is your SMTP Host
- Port No is Your SMTP PORT No
Run your Project and hit the End Point. Now Swagger UI Exposes the End Point
After hitting the endpoint now add the required information in the request body of the endpoint.
Now click on the execute button when the endpoint successfully sends the request then the status is == 200 so our email is successfully sent to the required email address.
In the case of the GMAIL address now click on the Spam folder and your email is there.
In the case of an Outlook/Microsoft Account, just click your Inbox and receive your email there.
Now, check your Email address inbox folder.