First, you are going to add a new email service, which will be used to send emails to users who have freshly registered on the website. Let's get started:
- Within the Services folder, add a new service called EmailService and implement a default SendEmail method, which we will update later:
public class EmailService { public Task SendEmail(string emailTo, string subject,
string message) { return Task.CompletedTask; } }
- Extract the IEmailService interface:
- Add the new email service to the ConfigureServices method of the Startup class (we want a single application instance, so add it as a singleton):
services.AddSingleton<IEmailService, EmailService>();
- Update UserRegistrationController so that it is able to access EmailService, which we created in the previous step:
readonly IUserService _userService; readonly IEmailService _emailService; public UserRegistrationController(IUserService userService,
IEmailService emailService) { _userService = userService; _emailService = emailService; }
- Update the EmailConfirmation method in UserRegistrationController so that you can call the SendEmail method of EmailService by inserting the following code between var user=await _userService.GetUserByEmail(email); and the user?.IsEmailConfirmed conditional statement check:
var user = await _userService.GetUserByEmail(email); var urlAction = new UrlActionContext { Action = "ConfirmEmail", Controller = "UserRegistration", Values = new { email }, Protocol = Request.Scheme, Host = Request.Host.ToString() }; var message = $"Thank you for your registration on
our website, please click here to confirm your
email " + $"
{Url.Action(urlAction)}"; try { _emailService.SendEmail(email,
"Tic-Tac-Toe Email Confirmation", message).Wait(); } catch (Exception e) { }
Great – you have an email service now, but you aren't done yet. You need to be able to configure the service so that you can set environment-specific parameters (SMTP server name, port, SSL, and more) and then send the emails.