ASP.NET MVC: Create a Registration Form with Email Confirmation

By FoxLearn 5/29/2017 8:51:39 PM   13.58K
How to Create a Registration Form with Email Confirmation in ASP.NET Identity MVC 5 using C#, Entity Framework Code First

Step 1: Open AccountController, then change Register action as below

//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, FullName = model.FullName, Gender = model.Gender };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            result = await UserManager.AddToRoleAsync(user.Id, model.RoleName);
            await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
            // Send an email with this link
            string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
            return RedirectToAction("Index", "Home");
        }
        AddErrors(result);
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}

Step 2: Open IdentityConfig, then change SendAsync method as below

public Task SendAsync(IdentityMessage message)
{
    // Plug in your email service here to send an email.
    //return Task.FromResult(0);
    return Task.Factory.StartNew(() =>
    {
        sendMail(message);
    });
}

void sendMail(IdentityMessage message)
{
    #region formatter
    string text = string.Format("Please click on this link to {0}: {1}", message.Subject, message.Body);
    string html = "Please confirm your account by clicking this link: <a href=\"" + message.Body + "\">link</a><br/>";
    html += HttpUtility.HtmlEncode(@"Or click on the copy the following link on the browser:" + message.Body);
    #endregion

    MailMessage msg = new MailMessage();
    msg.From = new MailAddress(ConfigurationManager.AppSettings["Email"].ToString());
    msg.To.Add(new MailAddress(message.Destination));
    msg.Subject = message.Subject;
    msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
    msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
    SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", Convert.ToInt32(587));
    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["Email"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
    smtpClient.Credentials = credentials;
    smtpClient.EnableSsl = true;
    smtpClient.Send(msg);
}

Step 3: Add Email and Password key to the appSettings section in the Web.config file

<appSettings>
    <add key="Email" value="your email"/>
    <add key="Password" value="your password"/>
</appSettings>

VIDEO TUTORIALS