I have been trying to figure out the easiest way of sending a confirmation email for when a user signs in!
I am using MailKit and Mailtrap.io (Sqlite and EF).
Below I have an example of the way I am doing it, and I can copy this the same way I have created it below onto my user controller. (I will put in the "What have you tried user controller"
My serviceSb looks like This:
public bool SendMail(string name, string email, string subject, string body)
{
var mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress("TheMailTrap", "manager@TheMailTrap.com"));
mailMessage.To.Add(new MailboxAddress(name, email));
mailMessage.Subject = subject;
mailMessage.Body = new TextPart("plain")
{
Text = body
};
try
{
var smtpClient = new SmtpClient();
smtpClient.Connect("smtp.mailtrap.io", 2525, SecureSocketOptions.StartTls);
smtpClient.Authenticate("61618d4d83c43242344d", "b5be3640923423434342f2afa");
smtpClient.Send(mailMessage);
smtpClient.Disconnect(true);
return true;
}
catch (Exception)
{
return false;
}
}
My Controller:
<pre lang="C#">
public IActionResult Create(Patient u)
{
if (svc.IsDuplicateEmailPatient(u.EmailAddress, u.Id))
{
ModelState.AddModelError(nameof(u.EmailAddress), "The Email is already in use");
}
if (ModelState.IsValid)
{
svc.AddPatient(u);
if (!svc.SendMail(u.Name, u.EmailAddress, "New Account", "THIS IS A TEST!!!! :D "))
{
Alert("Email Not Sent", AlertType.warning);
}
else
{
Alert("User Was Created. Email sent", AlertType.success);
}
return RedirectToAction(nameof(Index));
}
return View(u);
}
I am looking online at tutorials on how to do this but it is very different from the way I have been taught to implement this. I essentially want to make sure when someone registers into a particular role I want them to be made to wait before "Approved" by the manager - To make sure the role they register for is true!
However, if they register as a patient, for example, a confirmation email is sent and they can confirm it themselves.
Does anyone know the cleanest way of doing this? - My level of coding is a beginner and I have been losing days on looking at ways I think will work and then fails.
What I have tried:
Startup.cs
services.AddIdentity<User, IdentityRole>(opt =>
{
opt.Password.RequiredLength = 7;
opt.Password.RequireDigit = false;
opt.Password.RequireUppercase = false;
opt.User.RequireUniqueEmail = true;
opt.SignIn.RequireConfirmedEmail = true;
});
User Controller - This is where I am not sure how to implement the code?
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Register([Bind("Name,Email,Password,PasswordConfirm,Role")] UserRegisterViewModel m)
{
if (!ModelState.IsValid)
{
return View(m);
}
var user = _svc.AddUser(m.Name, m.Email,m.Password, m.Role);
if (user == null) {
Alert("There was a problem Registering. Please try again", AlertType.warning);
return View(m);
}
Alert("Successfully Registered. Now login", AlertType.info);
return RedirectToAction(nameof(Login));
}