Send confirmation email on registration in MVC

Send confirmation email on registering a new user in the application. In this article it is done with the help of entity framework database in MVC.

Please refer the article Simple User Login Form with Entity Framework in ASP.Net MVC to download the database script and to refer the “User” model.

User Model

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; }
 }

Controller

Below code is added in the home controller of the application.

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);
        }
    }
}

View

Right click on Index method to add view for the same.

@model Simple_Login_Form.User

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }

        table {
            border: 1px solid #ccc;
            border-collapse: collapse;
        }

        table th {
            background-color: #F7F7F7;
            color: #333;
            font-weight: bold;
        }

        table th, table td {
            padding: 5px;
            border: 1px solid #ccc;
        }

        .error {
            color: red;
        }
    </style>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <table border="0" cellpadding="0" cellspacing="0">
            <tr>
                <th colspan="3">
                    Registration
                </th>
            </tr>
            <tr>
                <td>
                    Username
                </td>
                <td>
                    @Html.TextBoxFor(m => m.Username)
                </td>
                <td>
                    @Html.ValidationMessageFor(m => m.Username, "", new { @class = "error" })
                </td>
            </tr>
            <tr>
                <td>
                    Password
                </td>
                <td>
                    @Html.PasswordFor(m => m.Password)
                </td>
                <td>
                    @Html.ValidationMessageFor(m => m.Password, "", new { @class = "error" })
                </td>
            </tr>
            <tr>
                <td>
                    Confirm Password
                </td>
                <td>
                    @Html.PasswordFor(m => m.ConfirmPassword)
                </td>
                <td>
                    @Html.ValidationMessageFor(m => m.ConfirmPassword, "", new { @class = "error" })
                </td>
            </tr>
            <tr>
                <td>
                    Email
                </td>
                <td>
                    @Html.TextBoxFor(m => m.Email)
                </td>
                <td>
                    @Html.ValidationMessageFor(m => m.Email, "", new { @class = "error" })
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="Submit" />
                </td>
                <td></td>
            </tr>
        </table>
    }
    @if (@ViewBag.Message != null)
    {
        <script type="text/javascript">
            $(function () {
                alert("@ViewBag.Message")
            });
        </script>
    }
</body>
</html>

Activate View

@{
    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>

Build and run the application. The output is displayed as shown below.

Send confirmation email

Register the user with the corresponding user details and mail will be send to corresponding email address which is specified during registration.