These days, most applications come with the ability to send email notifications. Sending an email in Dot Net is quite easy and can be accomplished using Simple Mail Transfer Protocol (SMTP). I have used SMTP in many of my web applications, and it is still available in .Net Core.
So, why should you use MailKit? While implementing the email function in one of my .Net Core projects, I found out that Microsoft had deemed SMTP to be outdated. Instead, they recommended using the MailKit library. For more information, please check out the link below.
I have used MailKit library in my .Net Core project.
Here I will share how to use simple email sending function using MailKit library in .Net Core projects.
After a successful installation, we can proceed further with the code.
1. Create a configuration class.
2. Add the mail server settings in appsettings.json file, like shown below.
3. Create one email message class.
4. To encapsulate email sending functionality and to use it anywhere from the application we should create one interface and class like given below.
5. Create a new class and inherit interface.
6. The code below is an implementation in class file EmailSender. Please don’t get confused with Smtp class used below in the code; this class belongs to MailKit library class. CreateEmailMessage method is a simple message creation method which we need to use to create a message using MimeMessage class.
7. In the .Net Core project, we need to add dependency injection in Startup.cs file.
8. Now we are ready to use the send method and can call this method from anywhere in the application.
The implementation provided above is for the synchronous method. Similarly, we need to implement an asynchronous method for the send function. We can also add code to be able to send emails with attachments.
When calling the send method, we can use a string for the message body or even a dynamic template file. The BodyBuilder class can be used to build the body or content of the email. It can also be used to add data from the template file and then change the dynamic content.
I developed this in a .Net Core project, but the recommendation is to use the MailKit library in all new developments, even if the project is in the .Net framework. In older implementations, we can replace existing SMTP code with MailKit.
Partner with MetaSys Software, the top DotNet development company, to build powerful and reliable software solutions that will drive your success. Contact us now to schedule a consultation and start your journey towards unparalleled growth!
- .Net Application Development
- .Net Core
- dot net
- Dot Net Core
- Dot Net Development
- dot net development services
- Dot Net Software Solutions
- DotNet Development Company