Sending emails is an integral part of web development and a better way to connect with your users and keep them up to date with notifications
Let’s have a walkthrough on how you can easily integrate email service in your Web API project in .Net Core easily using Mailkit and Smtp client
Start by creating a .Net Core Web Api Project in Visual Studio
CLICK ON Create a new project
Search for ASP.Net Core Web API, Select and click next
select as shown in the image
You can name your project to anything you want. I called mine EmailSender. then click next
Now let us integrate our Api project with Swagger UI for easy testing and a pretty interface, you can opt for Postman but I’ll recommend you follow the steps if you’re not very familiar with postman for testing.
You can install all 3 in your project.
You can check microsoft docs to find out about swagger
Now include the swagger service in your Configure Services in your Startup.cs class. You can change the title and contact and they are also optional.
add the app.UseSwagger and app.UseSwaggerUI in your Configure method in the same Startup.cs class
Add the smtp settings in your appsettings.json file and update the SenderEmail field and Password field with your credentials.
create a folder named model in your project and create SmtpSettings.cs class as shown below inside the folder or just create the class if you don’t want to include a folder.
We are going to be using this to read values in our appsettings.json file
Create A folder called interface and include an IEmailSender.cs Interface with the method SendEmailAsync
Create a folder called Service and include EmailSenderService.cs class as seen below to create your implementation.
You see how we are using the IOptions helper to read the values from appsettings with the SmtpSettings.cs we created earlier
We can now add our sender which is the same value (Our Gmail) from the appsettings.json, message subject, and recipient which is going to be passed in the method parameter when we run our project.
The message body: Note that I used an html message.. To send plain text, Just replace “html” with “plain”
Note: When we created an instance of SmtpClient, it uses the one from the Mailkit.Net.Smtp namespace.
If you try to use from another namespace, the methods (‘connect, disconnect and send may not be available)
o connect, we pass in the server which is smtp.gmail.com, and port which is 465 and we set usage of SSL to true
Now Create your controller like below EmailSenderController and follow the code steps
Now go back to your startup.cs and include
Set both launchurl to swagger
Run your code
Additional: Go to the Gmail account you are using, go to security settings, find less secured apps and allow. if you don’t allow less secure apps. Google may not allow you to be able to send messages for some reason.
After all is done.
Your email service should work perfectly.
Source: Medium - Habeeb Ajide
The Tech Platform