How to send email using ASP.NET Core 2.0
What Will I Learn?
In this tutorial I will show you how to send email using ASP.NET Core 2.0 in Web API project. It is useful e.g during reset password or forgot password in application. We will create service only for email according to S in SOLID, what define "single responsibility". What is more I will show you how to use dependency Injection in ASP.NET Core.
Requirements
- C#
- ASP.NET Core
- Visual Studio Core/ Visual Studio 2015+
Difficulty
- Intermediate
Tutorial Contents
Let's start!
At the beginning we have to create new project.
As I said earlier we will use ASP.NET Core Web Api, so we have to choose this:
Before we start crete logic we have to add to our appsetting.json some settings for our email client. In appsetings.json file:
In this file we will define our email, passwrd, host and port. It is neccessary because our application have to connect to our email and send message though him.
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"Email": {
"Email": "your@email.com",
"Password": "password",
"Host": "host",
"Port": "port"
}
}
For example for gmail Port is 587 and host: "smtp.gmail.com"
If We add email setting to appsetting.json file, we have to create new folder with 1 interface and 1 class. I named this folder: Services and in this folder is interface called IEmailSender and class EmailSender. I created interface because I want to show you Dependency Injection.
Dependency injection (DI) is a technique for achieving loose coupling between objects and their collaborators, or dependencies.
more You can read here
My project structure in this moment:
In IEmailSender we have to just define one method:
using System.Threading.Tasks;
namespace Email.Services
{
public interface IEmailService
{
Task SendEmail(string email, string message);
}
}
This method will take 3 strings:email, subject and message for our email.
In EmailSender class we have to implement our Interface and his method.
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace Email.Services
{
public class EmailService : IEmailService
{
private readonly IConfiguration _configuration;
public EmailService(IConfiguration configuration)
{
_configuration = configuration;
}
public async Task SendEmail(string email, string subject, string message)
{
using (var client = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = _configuration["Email:Email"],
Password = _configuration["Email:Password"]
};
client.Credentials = credential;
client.Host = _configuration["Email:Host"];
client.Port = int.Parse(_configuration["Email:Port"]);
client.EnableSsl = true;
using (var emailMessage = new MailMessage())
{
emailMessage.To.Add(new MailAddress(email));
emailMessage.From = new MailAddress(_configuration["Email:Email"]);
emailMessage.Subject = subject;
emailMessage.Body = message;
client.Send(emailMessage);
}
}
await Task.CompletedTask;
}
}
}
At the begining we have have constructor with take IConfiguration Interface as a parameter, and a private variable IConfiguration _configuration. It means that when we create new instance of EmailService we have initialize IConfiguration object, thanks him we can read our email settings.
Then we create method SendEmail with has 3 parameters, like in previous Interface. In this method we will use SmtpClient, it is library from ASP.NET Core for sending email. In this using we define our credentials for email - it is taken from our settings file. When we change our password or email we dont have to change code, just change our settings and everything will be working. Then we setting parameters to our client, and at the end we will send our email asynchronously.
Ok, we have all necessary methods, no we can create main method in our controller responsible for sending message.
Now we have to prepare our Controller for send email message, everything what we have to do is inject our IEmailSender in constructor.
private readonly IEmailService _emailService;
public AccountController(IEmailService emailService)
{
_emailService = emailService;
}
in Controller we will create new POST method:
[HttpPost]
[Route("account/send-email")]
public async Task<IActionResult> SendEmailAsync([FromUri]string email, string subject, string message)
{
await _emailService.SendEmail(email, subject, message);
return Ok();
}
Last thing what left is telling our application that when we use IEmailService we want to use EmailService methods. Everything what we have to do is change our startup.cs file:
in this way:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddTransient<IEmailService, EmailService>();
}
Curriculum
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Hey @babelek I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x