A few weeks ago we've published a post explaining how to send e-mail messages within any ASP.NET Core web application using MailKit, an Open Source cross-platform .NET mail-client library that allows to connect to any third-party SMTP server and send e-mail messages.
In this article we'll provide an alternative implementation that takes advantage of the NETCore.MailKit NuGet package and will allow us to achieve the same results with even less custom code.
Pick up where we left off
In the previous article we've seen how to perform the following steps:
- Create a TOptions class, which we've put in a dedicated MailKitEmailSenderOptions.cs file.
- Implement the MailKitEmailSender class (in the MailKitEmailSender.cs file).
- Add the MailKitEmailSender to the application pipeline (in the Startup.cs class) as a singleton instance.
Even if the above technique works fine, it can be greatly simplified using the NETCore.MailKit Nuget package, which basically already contains two ready-to-use TOptions and sender classes, as well as a dedicated middleware to add the sender to the application's pipeline without having to manually do that.
However, such "simplified" solution comes with a flaw that you might want to consider before digging into it: it does not implement the ASP.NET Core built-in IEmailSender interface, but it uses its own interface (IEmailService), which works in a very different way. This basically mean that it doesn't integrate with the ASP.NET Core Identity out of the box like the alternative method provided by our previous post.
For that very reason, if you're looking for a convenient IEmailSender implementation, we strongly suggest to stop reading this post now: conversely, if such issue is not relevant for your specific scenario - maybe because you don't need any ASP.NET Core Identity integration - then you might consider using this method to quickly make your web application able to send e-mail messages without having to write too much code.
1. Install NETCore.MailKit
The first thing we need to do is to install the NETCore.MailKit NuGet package, which can be done in the following ways:
- Using the .NET Core CLI, with the dotnet add package NETCore.MailKit console command from the ASP.NET Core project's root folder.
- Using the Visual Studio Package Manager Console, by typing Install-Package NETCore.MailKit in the Package Manager window panel: if such panel is not already present in the default GUI it can be made accessible from the main menu (View > Other Windows > Package Manager Console).
- Using the Visual Sutdio Package Manager GUI (from Solution Explorer, right-click to the project's root node and then select the Manage NuGet Packages option).
The latest version at the time of writing is 2.0.3, which is fully compatible with .NET Core 2, 3, 3.1 and 5: feel free to remove the -version switch if you want to use the package’s latest version.
Once NETCore.MailKit has been installed, we can move on to the next step.
Setup the SMTP settings
As explained in our previous post, the best place to store our SMTP server’s settings is in the our application.json file: such technique will allow us to configure our SMTP settings without having to put credentials and/or other potentially sensitive info within our code, and is therefore a highly recommended approach for security reasons; furthermore, such good practice will also allow us to securely define a separate SMTP configuration for our development environment by using the Visual Studio User Secrets feature.
Open the appsettings.json file and add the following block to the existing JSON:
1 2 3 4 5 6 7 8 9 10 11 12 |
"ExternalProviders": { "MailKit": { "SMTP": { "Address": "my-smtp.server.com", "Port": "465", "Account": "my-smtp-username", "Password": "my-smtp-password", "SenderName": "My Sender Name" } } } |
Be sure to replace the SMTP sample settings in the above code (address, port, and so on) with valid ones: it goes without saying that we need to have a valid SMTP server available: in case we don’t, we can use any free SMTP server provided by third-party e-mail delivery online services such as SendGrid, SendInBlue and so on.
Configure the Startup class
As soon as the appsettings.json (and/or secrets.json) settings are in place, we can implement the MailKit service within our Startup.cs class by adding the following lines at the end of the ConfigureService method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// IEmailService implementation using MailKit services.AddMailKit(optionBuilder => { optionBuilder.UseMailKit(new MailKitOptions() { Server = Configuration["ExternalProviders:MailKit:SMTP:Address"], Port = Convert.ToInt32(Configuration["ExternalProviders:MailKit:SMTP:Port"]), Account = Configuration["ExternalProviders:MailKit:SMTP:Account"], Password = Configuration["ExternalProviders:MailKit:SMTP:Password"], SenderEmail = Configuration["ExternalProviders:MailKit:SMTP:SenderEmail"], SenderName = Configuration["ExternalProviders:MailKit:SMTP:SenderName"], // Set it to TRUE to enable ssl or tls, FALSE otherwise Security = true }); }); |
For the above code to work without compiler errors, we’ll also need to add the following namespaces at the beginning of the file:
1 2 3 |
using NETCore.MailKit.Extensions; using NETCore.MailKit.Infrastructure.Internal; using System; |
Moreover, if you've already implemented the MailKitEmailSender using our first technique described here, be sure to comment it out, as it won't be needed anymore: you can even delete the home-made MailKitEmailSender.cs and MailKitEmailSenderOptions.cs classes if you want, unless you don't plan to use them for other purposes (such as provide an IEMailSender interface implementation for ASP.NET Core Identity).
Conclusions
That’s it: as we can easily see, in terms of "raw" e-mail sending capabilities this new MailKit implementation will work just like the previous one, while being definitely faster to implement thanks to the built-in option class and middleware provided by the NETCore.MailKit NuGet package: however, those who are looking for an actual IEMailSender implementation should likely keep the former implementation instead.
Note: this nuget package does not implement IEmailSender; it provides its own interface: IEmailService. So it does not properly integrate with Identity UI out of the box.
Hi Andrew,
thank you for your feedback! I’ve updated the post to better clarify your point to the reader, let me know what you think about the changes.