In this article I will explain with an example, 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.
Note: 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.
 
 

Database

I have made use of the following table UserActivation with the schema as follows.
Send user Confirmation email after Registration with Activation Link in ASP.Net
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 

Registration Page

HTML Markup

<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <th colspan="3">Registration</th>
    </tr>
    <tr>
        <td>Username</td>
        <td><asp:TextBox ID="txtUsername" runat="server" /></td>
        <td><asp:RequiredFieldValidator ID="rfvUsername" runat="server" ControlToValidate="txtUsername" ErrorMessage="Required" ForeColor="Red" /></td>
    </tr>
    <tr>
        <td>Password</td>
        <td><asp:TextBox ID="txtPassword" runat="server" TextMode="Password" /></td>
        <td><asp:RequiredFieldValidator ID="rfvPassword" runat="server" ErrorMessage="Required" ControlToValidate="txtPassword" ForeColor="Red" /></td>
    </tr>
    <tr>
        <td>Confirm Password</td>
        <td><asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" /></td>
        <td><asp:CompareValidator ID="cvConfirmPassword" runat="server" ControlToValidate="txtConfirmPassword" ControlToCompare="txtPassword" ErrorMessage="Passwords do not match." ForeColor="Red" /></td>
    </tr>
    <tr>
        <td>Email</td>
        <td><asp:TextBox ID="txtEmail" runat="server" /></td>
        <td>
            <asp:RequiredFieldValidator ID="rfvEmail" runat="server" ControlToValidate="txtEmail" ErrorMessage="Required" Display="Dynamic" ForeColor="Red" />
            <asp:RegularExpressionValidator ID="revEmail" runat="server" ControlToValidate="txtEmail" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                ErrorMessage="Invalid email address." ForeColor="Red" />
        </td>
    </tr>
    <tr>
        <td></td>
        <td><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="RegisterUser" /></td>
        <td></td>
    </tr>
</table>
 

Code-Behind

C#
protected void RegisterUser(object sender, EventArgs e)
{
    int userId = 0;
    string spName "Insert_User";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(spName))
        {
            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 alreadyexists.\\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(this.GetType(), "alert""alert('" + message + "');"true);
    }
}
 
VB.Net
Protected Sub RegisterUser(ByVal sender As ObjectByVal e As EventArgs)
    Dim userId As Integer = 0
    Dim spName As String "Insert_User"
    Dim constr As String ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(spName)
            Using sda As SqlDataAdapter = 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."
            Case -2
                 message = "Supplied email address has already been used."
            Case Else
                 message = "Registration successful. Activation email has been sent."
                 SendActivationEmail(userId)
        End Select
        ClientScript.RegisterStartupScript(Me.GetType(), "alert""alert('" & message & "');"True)
    End Using
End Sub
 
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.
 
SendActivationEmail 
This method accepts the UserId as a parameter inside which a unique Activation Code is generated using NewGuid method of the Guid class and it is inserted in the UserActivation table.
Finally, an email is sent to the user’s email address with the URL of the Activation page along with generated Activation Code in the QueryString of the URL.
Note: For more details on how to send email using Gmail SMTP in ASP.Net, please refer my article Send email using Gmail SMTP Mail Server in ASP.Net.
 
C#
private void SendActivationEmail(int userId)
{
    string sql = "INSERT INTO UserActivation VALUES (@UserId, @ActivationCode)";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string activationCode Guid.NewGuid().ToString();
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(sql, con))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                cmd.Parameters.AddWithValue("@UserId", userId);
                cmd.Parameters.AddWithValue("@ActivationCode", activationCode);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
        
    SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
    string  host = smtpSection.Network.Host;
    int port = smtpSection.Network.Port;
    bool enableSsl = smtpSection.Network.EnableSsl;
    bool defaultCredentials = smtpSection.Network.DefaultCredentials;
    string from = smtpSection.From;
    string password = smtpSection.Network.Password;
 
    using (MailMessage mm = new MailMessage(from, 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.";
        body += "<br /><br />Thanks";
        mm.Body = body;
        mm.IsBodyHtml = true;
        using (SmtpClient smtp = new SmtpClient())
        {
            smtp.Host = host;
            smtp.Port = port;
            smtp.EnableSsl = enableSsl;
            smtp.UseDefaultCredentials = defaultCredentials;
            NetworkCredential networkCred = new NetworkCredential(from, password);
            smtp.Credentials = networkCred;
            smtp.Send(mm);
        }
    }
}
 
VB.Net
Private Sub SendActivationEmail(ByVal userId As Integer)
    Dim sql As String "INSERT INTO UserActivation VALUES (@UserId, @ActivationCode)"
    Dim constr As String ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim activationCode As String Guid.NewGuid().ToString()
    Using con As SqlConnection =  New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(sql, con)
            Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
                cmd.Parameters.AddWithValue("@UserId", userId)
                cmd.Parameters.AddWithValue("@ActivationCode", activationCode)
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Using
 
    Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
    Dim host As String = smtpSection.Network.Host
    Dim port As Integer = smtpSection.Network.Port
    Dim enableSsl As Boolean = smtpSection.Network.EnableSsl
    Dim defaultCredentials As Boolean = smtpSection.Network.DefaultCredentials
    Dim from As String = smtpSection.From
    Dim password As String = smtpSection.Network.Password
 
    Using mm As MailMessage = New MailMessage(from, 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("CS.aspx", "CS_Activation.aspx?ActivationCode=" & activationCode) & "'>Click here to activate your account."
         body += "<br /><br />Thanks"
         mm.Body = body
         mm.IsBodyHtml = True
         Using smtp As SmtpClient = New SmtpClient()
            smtp.Host = host
            smtp.Port = port
            smtp.EnableSsl = enableSsl
            smtp.UseDefaultCredentials = defaultCredentials
            Dim networkCred As NetworkCredential =  New NetworkCredential(from, password)
            smtp.Credentials = networkCred
            smtp.Send(mm)
        End Using
    End Using
End Sub
 
 

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 following controls:
Literal – For displaying the Activation status message.
<h1><asp:Literal ID="ltMessage" runat="server" /></h1>
 
 

Namespaces

You will need to import the following namespaces.
C#
usingSystem.Data;
usingSystem.Configuration;
using System.Data.SqlClient;
 
VB.Net
ImportsSystem.Data
ImportsSystem.Configuration
ImportsSystem.Data.SqlClient
 
 

Validating the Activation Code and activating the User Account

Inside the Page Load event handler, the Activation Code is extracted from the QueryString.
Then, the extracted Activation Code is validated by checking if it exists in the UserActivation table.
If the Activation Code is exists then, the record is deleted from UserActivation table using ExecuteNonQuery method of SqlCommand class and an Activation status message will be displayed.
Note: For more details on ExecuteNonQuery in ASP.Net, please refer my article .
 
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string sql = "DELETE FROM UserActivation WHERE ActivationCode = @ActivationCode";
        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())
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
                {
                    cmd.Parameters.AddWithValue("@ActivationCode", activationCode);
                    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(ByVal sender As ObjectByVal e As EventArgs)
    If Not Me.IsPostBack Then
        Dim sql As String "DELETE FROM UserActivation WHERE ActivationCode = @ActivationCode"
        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 SqlConnection = New SqlConnection(constr)
            Using cmd As SqlCommand = New SqlCommand()
                Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
                    cmd.Parameters.AddWithValue("@ActivationCode", activationCode)
                    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
 
 

Screenshots

Inserted record in the UserActivation table

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
 

Message displayed when Activation is successful

Send user Confirmation email after Registration with Activation Link in ASP.Net  
 
 

Downloads