Wednesday 11 June 2014

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






Description:-

How to send user confirmation email after registration is complete in your website then Activation link is send to the user email to verify the user in ASP.Net using C# .Net.

also to validate the email Id of the user enter during registration fill up form, a confirmation email with activation link is sent to the email address as user enter in Registration and when user clicks on the Activation  link, his email address is verified and his account gets activated or started.

We all know very well today every website have this Email verification process to exclude the dummy user or for better security.

In this example we will explain that how to send user confirmation email after registration with Activation link in ASP.Net using C# .Net.


Here activation code is generated new every time when new user is registered when delete this activation code when user click on activation link means when user activate his account.

Concept of Email Activation

The overall concept of the email activation is fairly simple. User register then receive an e-mail that you have registered along with an activation URL.  When you click on the URL it goes to the website and activates your account proved that you are not dummy user and your e-mail address.

mvc example for display grand total in footer of webgrid Footer template in webgrid in mvc4

create awesome vertical menu using CSS Fancy vertical menu in CSS


Implement Remember Me functionality using CheckBox ASP.Net 

set WaterMark Text in PDF using itextsharp in C#

How to set Default Button in MVC Web Form Application 

How to Bind XML File data to Treeview in asp.net

JQuery datepicker calender with Dropdown month and year in asp.net.

Register.aspx:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Send user Confirmation email after Registration with Activation Link in ASP.Net
    </title>
    <style type="text/Registers">
        body
        {
            font-family: Arial;
            font-size: 11pt;
        }
        input
        {
            width: 220px;
        }
        table
        {
            border: 2px solid #bbb;
        }
        table th
        {
            background-color: #F7c8f7;
            color: #333;
            font-weight: bold;
        }
        table th, table td
        {
            padding: 4px;
            border-color: #ccc;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <th colspan="3">
                Registration
            </th>
        </tr>
        <tr>
            <td>
                UserId
            </td>
            <td>
                <asp:TextBox ID="txtUserId" runat="server" />
            </td>
            <td>
                <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtUserId"
                    runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                Password
            </td>
            <td>
                <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
            </td>
            <td>
                <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtPassword"
                    runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                Confirm Password
            </td>
            <td>
                <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" />
            </td>
            <td>
                <asp:CompareValidator ErrorMessage="Passwords do not match." ForeColor="Red" ControlToCompare="txtPassword"
                    ControlToValidate="txtConfirmPassword" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                Email Address
            </td>
            <td>
                <asp:TextBox ID="txtEmailAddressAddress" runat="server" />
            </td>
            <td>
                <asp:RequiredFieldValidator ErrorMessage="Required" Display="Dynamic" ForeColor="Red"
                    ControlToValidate="txtEmailAddressAddress" runat="server" />
                <asp:RegularExpressionValidator runat="server" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                    ControlToValidate="txtEmailAddress" ForeColor="Red" ErrorMessage="Enter Proper email address." />
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <asp:Button Text="Register" runat="server" OnClick="Register_User_click" />
            </td>
            <td>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Register.aspx.cs:-

using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net;

public partial class Register : System.Web.UI.Page
{
    protected void Register_User_click(object sender, EventArgs e)
    {
        int userId = 0;
        string constr = ConfigurationManager.ConnectionStrings["yourdatabaseconnectionstring"].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", txtUserId.Text.Trim());
                    cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
                    cmd.Parameters.AddWithValue("@Email", txtEmailAddress.Text.Trim());
                    cmd.Connection = con;
                    con.Open();
                    userId = Convert.ToInt32(cmd.ExecuteScalar());
                    con.Close();
                }
            }
            string message = string.Empty;
            switch (userId)
            {
                case -1:
                    message = "UserId already exists.Please Enter  a different userId.";
                    break;
                case -2:
                    message = "Supplied email address has already been used.";
                    break;
                default:
                    message = "Registration successful. Activation email has been sent to your Email Address.";
                    Sendactivecodetouser(userId);
                    break;
            }
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
        }
    }

    private void Sendactivecodetouser(int userId)
    {
        string constr = ConfigurationManager.ConnectionStrings["yourdatabaseconnectionstring"].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", txtEmailAddress.Text))
        {
            mm.Subject = "Account Activation";
            string body = "Hello " + txtUserId.Text.Trim() + ",";
            body += "<br /><br />Please click the following link to activate your account";
            body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("Register.aspx", "Register_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);
        }
    }
}

Register_Activation.aspx:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Register_Activation.aspx.cs"
    Inherits="Register_Activation" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Activition Email Address Form</title>
    <style type="text/Registers">
        body
        {
            font-family: Arial;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <h1>
        <asp:Literal ID="ltMessage" runat="server" /></h1>
    </form>
</body>
</html>


Register_Activation.aspx.cs:-

using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
public partial class Register_Activation : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            string constr = ConfigurationManager.ConnectionStrings["yourdatabaseconnectionstring"].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 now you can Login.";
                        }
                        else
                        {
                            ltMessage.Text = "Invalid Activation code.";
                        }
                    }
                }
            }
        }
    }

}

5 comments:

  1. wow great post..........

    ReplyDelete
  2. is it possible to sent me sql table with store procedure...

    thanks (aditraj1@gmail.com)

    ReplyDelete
    Replies
    1. hi i can not get what you say can you please describe in details what you want so I can update you if possible.

      Delete
    2. may i know ur database table?

      Delete
  3. Hi sir , may i know your database table

    ReplyDelete