Introduction
This post explains account confirmation with an ASP.NET MVC identity using an email template.
Prerequisites
- Knowledge of ASP.NET Identity
- Knowledge of ASP.NET MVC
Overview
I have created a sample ASP.NET MVC application with an identity. In this project, I will add features for account confirmation using an email template
Let's start our project. Create a new MVC project, as shown below
Now, enter a project name and select the project location and framework.
Click on the "Create" button. Now select the MVC application and authentication
Now, change authentication from "no authentication" to "individual user accounts" and click on the "Create" Button.
Now, your project is created successfully.
Go to web.config and write the connection string:
- <connectionStrings>
- <add name="Connect" connectionString="Data Source=*****; User id=****;password=****;Database=Demo" providerName="System.Data.SqlClient" />
- </connectionStrings>
Now, we create a send email functionality. Add a utility folder and create a SendEmail Class. In this method, we get Host,MailForm, Password and Port from a Web.Config File.
- using System;
- using System.Configuration;
- using System.Net;
- using System.Net.Mail;
- namespace DemoAccount.Utility
- {
- public class SendEmail
- {
- public static bool EmailSend(string SenderEmail, string Subject, string Message, bool IsBodyHtml = false)
- {
- bool status = false;
- try
- {
- string HostAddress = ConfigurationManager.AppSettings["Host"].ToString();
- string FormEmailId = ConfigurationManager.AppSettings["MailFrom"].ToString();
- string Password = ConfigurationManager.AppSettings["Password"].ToString();
- string Port = ConfigurationManager.AppSettings["Port"].ToString();
- MailMessage mailMessage = new MailMessage();
- mailMessage.From = new MailAddress(FormEmailId);
- mailMessage.Subject = Subject;
- mailMessage.Body = Message;
- mailMessage.IsBodyHtml = IsBodyHtml;
- mailMessage.To.Add(new MailAddress(SenderEmail));
- SmtpClient smtp = new SmtpClient();
- smtp.Host = HostAddress;
- smtp.EnableSsl = true;
- NetworkCredential networkCredential = new NetworkCredential();
- networkCredential.UserName = mailMessage.From.Address;
- networkCredential.Password = Password;
- smtp.UseDefaultCredentials = true;
- smtp.Credentials = networkCredential;
- smtp.Port = Convert.ToInt32(Port);
- smtp.Send(mailMessage);
- status = true;
- return status;
- }
- catch(Exception e)
- {
- return status;
- }
- }
- }
- }
For the mail host setting in the config file.- <appSettings>
- <add key="Host" value="smtp.gmail.com" />
- <add key="Port" value="587" />
- <add key="MailFrom" value="From-Email" />
- <add key="Password" value="From-Password" />
- </appSettings>
Here is account confirmation HTML template. In this template, I used Inline CSS.
The email and link are dynamic, so we have to add a value custom identity, such as {UserName} and {ConfirmationLink}
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
- <head>
- <meta name="viewport" content="width=device-width" />
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <title>WSS</title>
- <style type="text/css">
- img {
- max-width: 100%;
- }
- body {
- -webkit-font-smoothing: antialiased;
- -webkit-text-size-adjust: none;
- width: 100% !important;
- height: 100%;
- line-height: 1.6em;
- }
- body {
- background-color: #f6f6f6;
- }
- @media only screen and (max-width: 640px) {
- body {
- padding: 0 !important;
- }
- h1 {
- font-weight: 800 !important;
- margin: 20px 0 5px !important;
- }
- h2 {
- font-weight: 800 !important;
- margin: 20px 0 5px !important;
- }
- h3 {
- font-weight: 800 !important;
- margin: 20px 0 5px !important;
- }
- h4 {
- font-weight: 800 !important;
- margin: 20px 0 5px !important;
- }
- h1 {
- font-size: 22px !important;
- }
- h2 {
- font-size: 18px !important;
- }
- h3 {
- font-size: 16px !important;
- }
- .container {
- padding: 0 !important;
- width: 100% !important;
- }
- .content {
- padding: 0 !important;
- }
- .content-wrap {
- padding: 10px !important;
- }
- .invoice {
- width: 100% !important;
- }
- }
- </style>
- </head>
- <body itemscope itemtype="http://schema.org/EmailMessage" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; width: 100% !important; height: 100%; line-height: 1.6em; background-color: #f6f6f6; margin: 0;" bgcolor="#f6f6f6">
- <table class="body-wrap" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; width: 100%; background-color: #f6f6f6; margin: 0;" bgcolor="#f6f6f6">
- <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
- <td style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0;" valign="top"></td>
- <td class="container" width="600" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; display: block !important; max-width: 600px !important; clear: both !important; margin: 0 auto;" valign="top">
- <div class="content" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; max-width: 600px; display: block; margin: 0 auto; padding: 20px;">
- <table class="main" width="100%" cellpadding="0" cellspacing="0" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; border-radius: 3px; background-color: #fff; margin: 0; border: 1px solid #e9e9e9;" bgcolor="#fff">
- <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
- <td class="alert alert-warning" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 16px; vertical-align: top; color: #fff; font-weight: 500; text-align: center; border-radius: 3px 3px 0 0; background-color: #3c8dbc; margin: 0; padding: 20px;" align="center" bgcolor="#FF9F00" valign="top">
- Account Confirmation
- </td>
- </tr>
- <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
- <td class="content-wrap" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 20px;" valign="top">
- <table width="100%" cellpadding="0" cellspacing="0" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
- <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
- <td class="content-block" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
- Hello, <strong style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">{UserName}</strong>
- </td>
- </tr>
- <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
- <td class="content-block" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
- Please click bellow button for confirm your account.
- </td>
- </tr>
- <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
- <td class="content-block" style="">
- <a href="{ConfirmationLink}" class="btn-primary" style="background-color: #3c8dbc; border: none;color: white; padding: 10px 41px;text-align: center;text-decoration: none;display: inline-block; font-size: 16px;margin: 4px 2px;cursor: pointer;">Confirmation Link </a>
- </td>
- </tr>
- <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
- <td class="content-block" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
- <br /><b>Thanks & Regards,</b><br />
- Pritesh N Maturkar<br />
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table><div class="footer" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; width: 100%; clear: both; color: #999; margin: 0; padding: 20px;">
- <table width="100%" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
- <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
- <td class="aligncenter content-block" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 12px; vertical-align: top; color: #999; text-align: center; margin: 0; padding: 0 0 20px;" align="center" valign="top"></td>
- </tr>
- </table>
- </div>
- </div>
- </td>
- <td style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0;" valign="top"></td>
- </tr>
- </table>
- </body>
- </html>
Here is the registration method for registration of a user account and sending a confirmation email. In this register method, create a user using the ASP.NET identity method. Also, we need to add a user role in this method. First, create a role and then assign it to the user. Then, send an email confirmation link on the registration time. For send an email confirmation link, first get the HTML template and add a dynamic value, such as a username confirmation link. The ASP.NET identity generates a call-back URL, which sends in the email.
-
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Register(RegisterViewModel model)
- {
- if (ModelState.IsValid)
- {
- var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
- ApplicationDbContext context = new ApplicationDbContext();
- var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
- if (!roleManager.RoleExists("Admin"))
- {
- var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
- role.Name = "Admin";
- roleManager.Create(role);
- }
- var result = await UserManager.CreateAsync(user, model.Password);
- if (result.Succeeded)
- {
- var result1 = UserManager.AddToRole(user.Id, "Admin");
- await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
- string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
- var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
-
- string body = string.Empty;
- using (StreamReader reader = new StreamReader(Server.MapPath("~/MailTemplate/AccountConfirmation.html")))
- {
- body = reader.ReadToEnd();
- }
- body = body.Replace("{ConfirmationLink}", callbackUrl);
- body = body.Replace("{UserName}", model.Email);
- bool IsSendEmail = SendEmail.EmailSend(model.Email, "Confirm your account", body, true);
- if(IsSendEmail)
- return RedirectToAction("Login", "Account");
- }
- AddErrors(result);
- }
-
-
- return RedirectToAction("Login", "Account");
- }
Registration has created an identity table in your database
Now, on the login page, we check if the user account email is confirmed or not. Here is the login method in the account controller. In the login method, first, get the user base on email. Then, we check the user email confirmation. The ASP.NET Identity provides a method (IsEmailConfirmedAsync) for checking if the user email is confirmed or not.
-
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- var user = await UserManager.FindByEmailAsync(model.Email);
- if (user != null)
- {
- if (!await UserManager.IsEmailConfirmedAsync(user.Id))
- {
- ModelState.AddModelError("", "You must have a confirmed email to log on.");
- return View();
- }
- }
-
-
- var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
- switch (result)
- {
- case SignInStatus.Success:
- return RedirectToLocal(returnUrl);
- case SignInStatus.LockedOut:
- return View("Lockout");
- case SignInStatus.RequiresVerification:
- return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
- case SignInStatus.Failure:
- default:
- ModelState.AddModelError("", "Invalid login attempt.");
- return View(model);
- }
- }
Now, press F5 and run the project.
Now, click on register.
After registration, send account confirmation via email. For confirmation, you need to click on the link. When we click on the link, it calls the account confirm method and updates the email confirmation field in the database.
Now, go to the login page.
[Note: If the user is not confirmed, then the account will display the above message]. Here is the reference link
I hope, you liked this blog. If you have any doubts, you can ask me and I will try to answer your questions.