In this article I will explain with an example, how to send user confirmation email after registration with Activation link in ASP.Net MVC Razor. The Registration Form will save (insert) data to database using Entity Framework.
User will fill up the registration form with details such as username, password, email address, etc. and these details will be saved in the database table.
In order to validate the email address of the user provided during registration, a confirmation email with activation link in sent to the email address and when user clicks the link, his email address is verified and his account gets activated.
Note: This article is continuation of my previous article Simple User Registration Form with Entity Framework Database in ASP.Net MVC, where I have explained how to build a User registration form.
 
 
Configuring Bundles and enabling Client Side Validation
The User Registration Form validation will be performed on Client Side using Model Data Annotations and jQuery.
Please refer the following article for complete information on how to configure Bundles and enable Client Side validation in ASP.Net MVC project.
Note: By default the validation done using Data Annotation attributes is Server Side. And hence to make it work Client Side, the Client Side validation must be enabled.
 
 

Database
In the previous article we have already created database named LoginDB which contains the following table named Users in it. For this article I have created a new table named UserActivation.
ASP.Net MVC: Send user Confirmation email after Registration with Activation Link
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Adding new Table to the Entity Framework Data Model
The Entity Framework has been already configured in the previous article and hence we will continue with further step i.e. adding the new Table i.e. UserActivation to the existing Entity Framework Data Model.
To do so, open the User Data Model and then Right click on the User Table and click on the Update Model from Database option from the Context menu.
ASP.Net MVC: Send user Confirmation email after Registration with Activation Link
 
The above action will open the Update Wizard dialog window, where you will need to select the newly added UserActivation Table and click Finish button.
ASP.Net MVC: Send user Confirmation email after Registration with Activation Link
 
The Table will now be available in the Entity Framework Data Model.
ASP.Net MVC: Send user Confirmation email after Registration with Activation Link
 
 
Model
The Model class User.cs remains the same as the previous article, but since the Entity Framework Data Model was modified it will overwrite the changes done for validations and hence, open the User.cs class and copy the following contents again.
namespace User_Activation_MVC
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
 
    public partial class User
    {
        public int UserId { get; set; }
 
        [Required(ErrorMessage = "Required.")]
        public string Username { get; set; }
 
        [Required(ErrorMessage = "Required.")]
        public string Password { get; set; }
 
        [Required(ErrorMessage = "Required.")]
        [Compare("Password", ErrorMessage = "Passwords do not match.")]
        public string ConfirmPassword { get; set; }
 
        [Required(ErrorMessage = "Required.")]
        [EmailAddress(ErrorMessage = "Invalid email address.")]
        public string Email { get; set; }
       
        public System.DateTime CreatedDate { get; set; }
       
        public Nullable<System.DateTime> LastLoginDate { get; set; }
    }
}
 
 
 
Namespaces
You will need to import the following namespaces.
using System.Linq;
using System.Net;
using System.Net.Mail;
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling POST operation for Registration
This action method remains same as the previous article, the only change is that now if the Registration is successful then a new method SendActivationEmail is called.
Inside the SendActivationEmail method, a unique Activation code is generated using NewGuid method of the Guid class and it is inserted in the UserActivation table.
Then an email is sent to the user’s email address with the URL of the Activation View along with generated Activation Code in the URL.
 
Action method for handling GET operation for Activation
When the user clicks the Activation link in the received email he will be redirected to the Activation View.
The Activation Code will be extracted from the Route Data Dictionary and using the Activation Code, the record will be fetched from the UserActivation table.
If the record exists i.e. it is valid then it will be deleted from the UserActivation table and user will be displayed a success message using ViewBag object.
public class HomeController : Controller
{
    // GET: Registration
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(User user)
    {
        UsersEntities usersEntities = new UsersEntities();
        usersEntities.Users.Add(user);
        usersEntities.SaveChanges();
        string message = string.Empty;
        switch (user.UserId)
        {
            case -1:
                message = "Username already exists.\\nPlease choose a different username.";
                break;
            case -2:
                message = "Supplied email address has already been used.";
                break;
            default:
                message = "Registration successful.\\nUser Id: " + user.UserId.ToString();
                SendActivationEmail(user);
                break;
        }
        ViewBag.Message = message;
 
        return View(user);
    }
 
    public ActionResult Activation()
    {
        ViewBag.Message = "Invalid Activation code.";
        if (RouteData.Values["id"] != null)
        {
            Guid activationCode = new Guid(RouteData.Values["id"].ToString());
            UsersEntities usersEntities = new UsersEntities();
            UserActivation userActivation = usersEntities.UserActivations.Where(p => p.ActivationCode == activationCode).FirstOrDefault();
            if (userActivation != null)
            {
                usersEntities.UserActivations.Remove(userActivation);
                usersEntities.SaveChanges();
                ViewBag.Message = "Activation successful.";
            }
        }
 
        return View();
    }
 
    private void SendActivationEmail(User user)
    {
        Guid activationCode = Guid.NewGuid();
        UsersEntities usersEntities = new UsersEntities();
        usersEntities.UserActivations.Add(new UserActivation
        {
            UserId = user.UserId,
            ActivationCode = activationCode
        });
        usersEntities.SaveChanges();
 
        using (MailMessage mm = new MailMessage("sender@gmail.com", user.Email))
        {
            mm.Subject = "Account Activation";
            string body = "Hello " + user.Username + ",";
            body += "<br /><br />Please click the following link to activate your account";
            body += "<br /><a href = '" + string.Format("{0}://{1}/Home/Activation/{2}", Request.Url.Scheme, Request.Url.Authority, activationCode) + "'>Click here to activate your account.</a>";
            body += "<br /><br />Thanks";
            mm.Body = body;
            mm.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            NetworkCredential NetworkCred = new NetworkCredential("sender@gmail.com", "<password>");
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mm);
        }
    }
}
 
 
Views
Index
This View consists of the Registration Form and it remains the same and the complete explanation is available in the previous article.
Activation
The Activation View simply displays the message set in the ViewBag object.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Activation</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <div>
        <h1>@ViewBag.Message</h1>
    </div>
</body>
</html>
 
 
Screenshots
Inserted record in the UserActivation table
ASP.Net MVC: Send user Confirmation email after Registration with Activation Link
 
Activation email sent to the user
ASP.Net MVC: Send user Confirmation email after Registration with Activation Link
 
Message displayed when Activation is successful
ASP.Net MVC: Send user Confirmation email after Registration with Activation Link
 
 
Downloads