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






dhanush kodiPosted Feb 3, 2023, 2:20 PM
Please claify what is "Host": "?????????", "Port": ?????? and how to find it?
v rPosted Oct 27, 2022, 2:46 PM
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
v rPosted Oct 27, 2022, 2:46 PM
This is the error message i m getting some times
v rPosted Oct 27, 2022, 2:46 PM
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
v rPosted Oct 27, 2022, 2:29 PM
Hi i have tried the same unfortunately i dint receive mail to specified email address. I m not getting any message. Double checked port number, host name with google support page also
albin rajappaPosted Jul 21, 2022, 9:56 PM
Do we have any samples for queueing emails
Dhiren PathakPosted May 31, 2022, 7:03 AM
Can i Use this code into Submit button to Auto Generate Mail from Page ???
kishor patilPosted May 22, 2022, 7:38 AM
Sir I am getting this exception ArgumentException: Cannot instantiate implementation type 'MailKit.MailService' for service type 'MailKit.IMailService'.
Abdul YasarPosted Nov 2, 2021, 6:06 PM
Sir I'm getting an Exception Which throws Invaild URI, The Host name could not be parsed. I'm Struck with this sir kindly give me a solution for this
Deep KumarPosted Oct 28, 2021, 1:33 PM
Sir I'm getting an error that "Fetch error undefined /swagger/v1/swagger.json".
sayyad hasanPosted Jul 7, 2021, 8:38 AM
Excellent article, sir I'm facing an issue while using my personal domain to send email Error: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. xxx.xxx.xxx.xx:587
jonathan ferreiraPosted Jul 5, 2021, 11:56 PM
Hello! Sr. I have a doubt, when I was tried to send a email I saw this project spend a lot of a time, almost 7seconds. You think, is it better to use a design pattern singleton? if yes, how can i implement this? I sorry for my english, i am learn yet. att.