This article is continuation of my previous article Simple User Registration Form Example in ASP.Net, where I have explained how to build a User registration form.
In this article I will explain how to send user confirmation email after registration with Activation link in ASP.Net using C# and VB.Net.
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.
 
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.
Send user Confirmation email after Registration with Activation Link in ASP.Net
In the above table column UserId is set as primary key and as well as foreign key to the Users table.
Note: The SQL for creating the database is provided in the attached sample code.
 
 
Registration Page
Note: The registration page has already been explained in my previous article Simple User Registration Form Example in ASP.Net, and hence here only necessary code and explanations (required for this article) are provided.
On the registration page I have made some changes in the RegisterUser event handler, if the username and email address are found valid then the SendActivationEmail method is executed (show highlighted in the code snippet below).
C#
protected void RegisterUser(object sender, EventArgs e)
{
    int userId = 0;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Insert_User"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim());
                cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
                cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                cmd.Connection = con;
                con.Open();
                userId = Convert.ToInt32(cmd.ExecuteScalar());
                con.Close();
            }
        }
        string message = string.Empty;
        switch (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. Activation email has been sent.";
                SendActivationEmail(userId);
                break;
        }
        ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
    }
}
 
VB.Net
Protected Sub RegisterUser(sender As Object, e As EventArgs)
    Dim userId As Integer = 0
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand("Insert_User")
            Using sda As New SqlDataAdapter()
                cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim())
                cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim())
                cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim())
                cmd.Connection = con
                con.Open()
                userId = Convert.ToInt32(cmd.ExecuteScalar())
                con.Close()
            End Using
        End Using
        Dim message As String = String.Empty
        Select Case userId
            Case -1
                message = "Username already exists.\nPlease choose a different username."
                Exit Select
            Case -2
                message = "Supplied email address has already been used."
                Exit Select
            Case Else
                message = "Registration successful. Activation email has been sent."
                SendActivationEmail(userId)
                Exit Select
        End Select
        ClientScript.RegisterStartupScript([GetType](), "alert", (Convert.ToString("alert('") & message) + "');", True)
    End Using
End Sub
 
Inside the SendActivationEmail method, a unique Activation code is generated using Guid’s NewGuid method 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 page with generated Activation Code in the QueryString of the URL.
C#
private void SendActivationEmail(int userId)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string activationCode = Guid.NewGuid().ToString();
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO UserActivation VALUES(@UserId, @ActivationCode)"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@UserId", userId);
                cmd.Parameters.AddWithValue("@ActivationCode", activationCode);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
    using (MailMessage mm = new MailMessage("sender@gmail.com", txtEmail.Text))
    {
        mm.Subject = "Account Activation";
        string body = "Hello " + txtUsername.Text.Trim() + ",";
        body += "<br /><br />Please click the following link to activate your account";
        body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("CS.aspx", "CS_Activation.aspx?ActivationCode=" + 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);
    }
}
 
VB.Net
Private Sub SendActivationEmail(userId As Integer)
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim activationCode As String = Guid.NewGuid().ToString()
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand("INSERT INTO UserActivation VALUES(@UserId, @ActivationCode)")
            Using sda As New SqlDataAdapter()
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("@UserId", userId)
                cmd.Parameters.AddWithValue("@ActivationCode", activationCode)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Using
    Using mm As New MailMessage("sender@gmail.com", txtEmail.Text)
        mm.Subject = "Account Activation"
        Dim body As String = "Hello " + txtUsername.Text.Trim() + ","
        body += "<br /><br />Please click the following link to activate your account"
        body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("VB.aspx", Convert.ToString("VB_Activation.aspx?ActivationCode=") & activationCode) + "'>Click here to activate your account.</a>"
        body += "<br /><br />Thanks"
        mm.Body = body
        mm.IsBodyHtml = True
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        smtp.EnableSsl = True
        Dim NetworkCred As New NetworkCredential("sender@gmail.com", "<password>")
        smtp.UseDefaultCredentials = True
        smtp.Credentials = NetworkCred
        smtp.Port = 587
        smtp.Send(mm)
    End Using
End Sub
 
Send user Confirmation email after Registration with Activation Link in ASP.Net
 
Activation email sent to the user
Send user Confirmation email after Registration with Activation Link in ASP.Net
 
 
Activation Page
When the user clicks the Activation link in the received email he will be land on this page, here the activation code will be validated and if it is valid user’s account will be activated.
 
HTML Markup
The HTML markup consists of an ASP.Net Literal control to display the Activation status message.
<h1><asp:Literal ID="ltMessage" runat="server" /></h1>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
 
 
Validating the Activation Code and activating the User Account
Inside the Page Load event of the page, the activation code is extracted from QueryString and delete query is executed on the UserActivation table with the extracted Activation Code.
If the activation code is valid, the record is deleted and the rows affected is 1. And if the activation code is invalid or the user has been already activated then no record is deleted and rows affected is returned 0.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string activationCode = !string.IsNullOrEmpty(Request.QueryString["ActivationCode"]) ? Request.QueryString["ActivationCode"] : Guid.Empty.ToString();
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("DELETE FROM UserActivation WHERE ActivationCode = @ActivationCode"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@ActivationCode", activationCode);
                    cmd.Connection = con;
                    con.Open();
                    int rowsAffected = cmd.ExecuteNonQuery();
                    con.Close();
                    if (rowsAffected == 1)
                    {
                        ltMessage.Text = "Activation successful.";
                    }
                    else
                    {
                        ltMessage.Text = "Invalid Activation code.";
                    }
                }
            }
        }
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim activationCode As String = If(Not String.IsNullOrEmpty(Request.QueryString("ActivationCode")), Request.QueryString("ActivationCode"), Guid.Empty.ToString())
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand("DELETE FROM UserActivation WHERE ActivationCode = @ActivationCode")
                Using sda As New SqlDataAdapter()
                    cmd.CommandType = CommandType.Text
                    cmd.Parameters.AddWithValue("@ActivationCode", activationCode)
                    cmd.Connection = con
                    con.Open()
                    Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
                    con.Close()
                    If rowsAffected = 1 Then
                        ltMessage.Text = "Activation successful."
                    Else
                        ltMessage.Text = "Invalid Activation code."
                    End If
                End Using
            End Using
        End Using
    End If
End Sub
 
Send user Confirmation email after Registration with Activation Link in ASP.Net
 
 
Downloads