Take advantage of the open source MailKit library to send emails in ASP.NET Core easily. Credit: Molnia/iStock You will often have the need to send emails through your application. You can take advantage of the MailKit NuGet package to send emails in ASP.NET Core. MailKit is an open source mail client library that can be used in .NET or .NET Core applications running on Windows, Linux, or Mac systems. This article presents a discussion of how we can use the MailKit NuGet package to send emails in ASP.NET Core. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. Create an ASP.NET Core API project First off, let’s create an ASP.NET Core project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed. Click Next. In the “Configure your new project” window shown next, specify the name and location for the new project. Click Create. In the “Create New ASP.Net Core Web Application” window, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top. I’ll be using ASP.NET Core 3.0 here. Select “API” as the project template to create a new ASP.NET Core API application. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either. Click Create. This will create a new ASP.NET Core API project in Visual Studio. Select the Controllers solution folder in the Solution Explorer window and click “Add -> Controller…” to create a new controller named DefaultController. We’ll use this project in the subsequent sections of this article. Install the MailKit NuGet package To work with MailKit, you should install the MailKit package from NuGet. You can do this either via the NuGet package manager inside the Visual Studio 2019 IDE, or by executing the following command at the NuGet package manager console: Install-Package NETCore.MailKit You will also need to add references to the following namespaces in your code: using MailKit.Net.Smtp; using MimeKit; Specify email configuration metadata in ASP.NET Core The following code snippet shows how you can specify the email configuration details in the appsettings.json file. "NotificationMetadata": { "Sender": "sender_email@gmail.com", "SmtpServer": "smtp.gmail.com", "Reciever": "receiver_email@yahoo.com", "Port": 465, "Username": "sender_email_user@gmail.com", "Password": "specify your password here" } To read the email configuration data, we will take advantage of the following class. public class NotificationMetadata { public string Sender { get; set; } public string Reciever { get; set; } public string SmtpServer { get; set; } public int Port { get; set; } public string UserName { get; set; } public string Password { get; set; } } Here’s how you can read the email configuration data from the appsettings.json file into an instance of NotificationMetadata class. public void ConfigureServices(IServiceCollection services) { var notificationMetadata = Configuration.GetSection("NotificationMetadata"). Get<NotificationMetadata>(); services.AddSingleton(notificationMetadata); services.AddControllers(); } Create an instance of the EmailMessage class in ASP.NET Core Create a new class named EmailMessage with the following code: public class EmailMessage { public MailboxAddress Sender { get; set; } public MailboxAddress Reciever { get; set; } public string Subject { get; set; } public string Content { get; set; } } Create an instance of the MimeMessage class in ASP.NET Core The following method illustrates how you can create a MimeMessage instance from an instance of our custom class EmailMessage. private MimeMessage CreateMimeMessageFromEmailMessage(EmailMessage message) { var mimeMessage = new MimeMessage(); mimeMessage.From.Add(message.Sender); mimeMessage.To.Add(message.Reciever); mimeMessage.Subject = message.Subject; mimeMessage.Body = new TextPart(MimeKit.Text.TextFormat.Text) { Text = message.Content }; return mimeMessage; } Send emails synchronously using MailKit in ASP.NET Core To send out an email, we need to take advantage of the SmtpClient class pertaining to the MailKit.Net.Smtp namespace. The following code snippet illustrates how this can be done. using (SmtpClient smtpClient = new SmtpClient()) { smtpClient.Connect(_notificationMetadata.SmtpServer, _notificationMetadata.Port, true); smtpClient.Authenticate(_notificationMetadata.UserName, _notificationMetadata.Password); smtpClient.Send(mimeMessage); smtpClient.Disconnect(true); } Here is the complete code of the Get action method of our DefaultController class for your convenience. public string Get() { EmailMessage message = new EmailMessage(); message.Sender = new MailboxAddress("Self", _notificationMetadata.Sender); message.Reciever = new MailboxAddress("Self", _notificationMetadata.Reciever); message.Subject = "Welcome"; message.Content = "Hello World!"; var mimeMessage = CreateEmailMessage(message); using (SmtpClient smtpClient = new SmtpClient()) { smtpClient.Connect(_notificationMetadata.SmtpServer, _notificationMetadata.Port, true); smtpClient.Authenticate(_notificationMetadata.UserName, _notificationMetadata.Password); smtpClient.Send(mimeMessage); smtpClient.Disconnect(true); } return "Email sent successfully"; } Send emails asynchronously using MailKit in ASP.NET Core The following code snippet illustrates an asynchronous version of the code we just wrote to send emails synchronously. using (SmtpClient smtpClient = new SmtpClient()) { await smtpClient.ConnectAsync(_notificationMetadata.SmtpServer, _notificationMetadata.Port, true); await smtpClient.AuthenticateAsync(_notificationMetadata.UserName, _notificationMetadata.Password); await smtpClient.SendAsync(mimeMessage); await smtpClient.DisconnectAsync(true); } Finally, note that MailKit also allows you to send emails using templates and even emails that have attachments. I will demonstrate the additional features of MailKit in a future article here. Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos