How to Send an Email with Verification link to user in Asp.net after registration - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial


How to Send an Email with Verification link to user in Asp.net after registration

In this post I will try to explain how we can send the verification Email with link to user after registration in Asp.net.
Send an Email with Verification link

Description:
In the previous article i have explained  How to Send Email with Attachment in Asp.net ,How to send Email in Asp.net using Web.config.
Here I created a table USER_REGISTRATION. USER_ID is primary key.

USER_ID
int
USERNAME
varchar(50)
FIRST_NAME
varchar(50)
LAST_NAME
varchar(50)
EMAIL
varchar(50)
IS_APPROVE
bit
PASSWORD
varchar(50)

Add two webforms to project User_registration.aspx and Verification.aspx.
Drag and drop the controls from Toolbox to .aspx page.
  <table border="1px solid" width="330px">
    <tr><b style="color:Blue;">Send Verification link to User after Registartion</b></tr>
    <tr><td>Username:</td><td>
        <asp:TextBox ID="txtusername" runat="server"></asp:TextBox></td></tr>
    <tr><td>First Name:</td><td>
        <asp:TextBox ID="txtfirst" runat="server"></asp:TextBox></td></tr>
    <tr><td>Last Name:</td><td>
        <asp:TextBox ID="txtlast" runat="server"></asp:TextBox></td></tr>
    <tr><td>Email:</td><td>
        <asp:TextBox ID="txtemail" runat="server"></asp:TextBox></td></tr>
    <tr><td>Password:</td><td>
        <asp:TextBox ID="txtpassword" runat="server" TextMode="Password"></asp:TextBox></td></tr>
    <tr><td>Confirm Password:</td><td>
        <asp:TextBox ID="txtconfirm" runat="server" TextMode="Password"></asp:TextBox></td></tr>
    <tr><td>&nbsp;</td><td>
        <asp:Button ID="Button1" runat="server" Text="Register" OnClientClick="return ValidateEmail();"
            onclick="Button1_Click" /></td></tr>
    </table>

Add the below given Javascript between Head Tag to validate the Email Textbox:
<script language="javascript" type="text/javascript">
         function ValidateEmail() {
             var emailRegex = new RegExp(/^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$/i);
             var emailAddress = document.getElementById("<%= txtemail.ClientID %>").value;
             var valid = emailRegex.test(emailAddress);
             if (!valid) {
                 alert("Please Enter Valid Email address");
                 return false;
             } else
                 return true;
         }
  </script>

Now go to .aspx.cs page and write the below mention code:

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

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString()); 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (IsUsernameEmailExist())
        {
           
            Messagebox("Username/Email address already exists. Please try another");
            return;
        }
        if (txtpassword.Text == txtconfirm.Text)
        {
            SqlCommand cmd = new SqlCommand("insert into USER_REGISTRATION (USERNAME,FIRST_NAME,LAST_NAME,EMAIL,PASSWORD) values(@USERNAME,@FIRST_NAME,@LAST_NAME,@EMAIL,@PASSWORD)", con);
            cmd.Parameters.AddWithValue("@USERNAME", txtusername.Text);
            cmd.Parameters.AddWithValue("@FIRST_NAME", txtfirst.Text);
            cmd.Parameters.AddWithValue("@LAST_NAME", txtlast.Text);
            cmd.Parameters.AddWithValue("@EMAIL", txtemail.Text);
            cmd.Parameters.AddWithValue("@PASSWORD", txtpassword.Text);
            cmd.ExecuteNonQuery();
            Sendemail();
            Clear();
            Messagebox("User Register Successfully");
            cmd.Dispose();
      
        }
        else
        {
            Messagebox("Passowrd Not Match");
        }                 
    }

    public void Sendemail()
    {
        string ActivationUrl;
        try
        {
            MailMessage message = new MailMessage();
            message.From = new MailAddress("demo@gmail.com", "Saklani");
            message.To.Add(txtemail.Text);
            message.Subject = "Verification Email";
            ActivationUrl = Server.HtmlEncode("http://localhost:9525/Important_Testing/Verification.aspx?USER_ID=" + GetUserID(txtemail.Text));
            message.Body = "<a href='"+ActivationUrl+"'>Click Here to verify your acount</a>";
            message.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.Credentials = new System.Net.NetworkCredential("demo@gmail.com", "demo123");
            smtp.EnableSsl = true;
            smtp.Send(message);
        }
        catch (Exception ex)
        {
        }
    }
    private string GetUserID(string Email)
    {
        SqlCommand cmd = new SqlCommand("SELECT USER_ID FROM USER_REGISTRATION WHERE EMAIL=@EMAIL", con);     
        cmd.Parameters.AddWithValue("@EMAIL", txtemail.Text);
        string UserID = cmd.ExecuteScalar().ToString();
        return UserID;
    }

    private bool IsUsernameEmailExist()
    {
        SqlCommand cmd = new SqlCommand("Select * from USER_REGISTRATION where USERNAME='" + txtusername.Text + "' or EMAIL='" + txtemail.Text + "'", con);
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    private void Messagebox(string Message)
    {
        Label lblMessageBox = new Label();

        lblMessageBox.Text =
            "<script language='javascript'>" + Environment.NewLine +
            "window.alert('" + Message + "')</script>";

        Page.Controls.Add(lblMessageBox);

    }
  public void Clear()
    {
        txtusername.Text = "";
        txtfirst.Text = "";
        txtlast.Text = "";
        txtemail.Text = "";
        txtpassword.Text = "";
        txtconfirm.Text = "";
    }

In VB (.aspx.vb)

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Net.Mail

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ToString())

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If con.State = ConnectionState.Closed Then
            con.Open()
        End If
    End Sub
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        If IsUsernameEmailExist() Then

            Messagebox("Username/Email address already exists. Please try another")
            Return
        End If
        If txtpassword.Text = txtconfirm.Text Then
            Dim cmd As New SqlCommand("insert into USER_REGISTRATION (USERNAME,FIRST_NAME,LAST_NAME,EMAIL,PASSWORD) values(@USERNAME,@FIRST_NAME,@LAST_NAME,@EMAIL,@PASSWORD)", con)
            cmd.Parameters.AddWithValue("@USERNAME", txtusername.Text)
            cmd.Parameters.AddWithValue("@FIRST_NAME", txtfirst.Text)
            cmd.Parameters.AddWithValue("@LAST_NAME", txtlast.Text)
            cmd.Parameters.AddWithValue("@EMAIL", txtemail.Text)
            cmd.Parameters.AddWithValue("@PASSWORD", txtpassword.Text)
            cmd.ExecuteNonQuery()
            Sendemail()
            Messagebox("User Register Successfully")

            cmd.Dispose()
        Else
            Messagebox("Passowrd Not Match")
        End If
    End Sub
    Private Function IsUsernameEmailExist() As Boolean
        Dim cmd As New SqlCommand(("Select * from USER_REGISTRATION where USERNAME='" + txtusername.Text & "' or EMAIL='") + txtemail.Text & "'", con)
        cmd.ExecuteNonQuery()
        Dim dt As New DataTable()
        Dim adp As New SqlDataAdapter(cmd)
        adp.Fill(dt)
        If dt.Rows.Count > 0 Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Sub Messagebox(ByVal Message As String)
        Dim lblMessageBox As New Label()

        lblMessageBox.Text = "<script language='javascript'>" + Environment.NewLine & "window.alert('" & Message & "')</script>"

        Page.Controls.Add(lblMessageBox)

    End Sub

 
    Public Sub Sendemail()
        Dim ActivationUrl As String
        Try
            Dim message As New MailMessage()
            message.From = New MailAddress("demo@gmail.com", "Saklani")
            message.[To].Add(txtemail.Text)
            message.Subject = "Verification Email"
            ActivationUrl = Server.HtmlEncode("http://localhost:9525/Important_Testing/Verification.aspx?USER_ID=" & GetUserID(txtemail.Text))
            message.Body = "<a href='" & ActivationUrl & "'>Click Here to verify your acount</a>"
            message.IsBodyHtml = True
            Dim smtp As New SmtpClient()
            smtp.Host = "smtp.gmail.com"
            smtp.Port = 587
            smtp.Credentials = New System.Net.NetworkCredential("demo@gmail.com", "demo123")
            smtp.EnableSsl = True
            smtp.Send(message)
        Catch ex As Exception
        End Try
    End Sub
    Private Function GetUserID(ByVal Email As String) As String
        Dim cmd As New SqlCommand("SELECT USER_ID FROM USER_REGISTRATION WHERE EMAIL=@EMAIL", con)
        cmd.Parameters.AddWithValue("@EMAIL", txtemail.Text)
        Dim UserID As String = cmd.ExecuteScalar().ToString()
        Return UserID
    End Function


After that now check the QueryString value on Verification.aspx page. Write the below given code on .aspx.cs page:

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
    string USERID, USERNAME;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["USER_ID"] != null)
        {
            USERID = Request.QueryString["USER_ID"];
            SqlCommand cmd = new SqlCommand("Update USER_REGISTRATION set IS_APPROVE=1 where USER_ID=@USER_ID", con);
            cmd.Parameters.AddWithValue("@USER_ID", USERID);          
            con.Open();
            cmd.ExecuteNonQuery();
            Response.Write(Request.QueryString["USER_ID"]);
        }
    }

In VB (.aspx.vb)

Imports System.Data
Imports System.Data.SqlClient

Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ToString())
    Private USERID As String, USERNAME As String
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Request.QueryString("USER_ID") IsNot Nothing Then
            USERID = Request.QueryString("USER_ID")
            Dim cmd As New SqlCommand("Update USER_REGISTRATION set IS_APPROVE=1 where USER_ID=@USER_ID", con)
            cmd.Parameters.AddWithValue("@USER_ID", USERID)
            con.Open()
            cmd.ExecuteNonQuery()
            Response.Write(Request.QueryString("USER_ID"))
        End If
    End Sub

Now run the project and check the result.

Download the project:

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+
loading...

26 comments

not yet tried, this was usefull, i am trying now.

Thanks for your appreciation. keep reading for more useful articles.

Hi friend... nice article... You really delivered nice content...

Viyali
https://www.facebook.com/pages/Viyali/654831647870191

Thanks. keep reading for more articles like this...

I got this site from my friend who shared with
me regarding this site and now this time I am visiting this web page and reading very informative
articles or reviews at this time.

My homepage; buy kamagra ireland

Juust wixh to say your article is aas astonishing.
The clearnerss in your post is simply grea and i can assume you're an expert on this subject.
Fine with your permission allow me to grab yokur RSS feed to keep updated with
forthcoming post. Thaks a million annd please carry on the rewarding work.


Check out my page; el cajon ca cosmetic dentist

What's up to all, the contents present at this web page are really
remarkable for people experience, well, keep up the nice work fellows.



Also visit my web site: cheap seo services company

Be very detailed and descriptive in your post, and try and target topics people will be searching for.
Author unknown, "Butterfly Watching in Nepal," Nepal. Probloggers (professional bloggers) are people who make money from blogging (as an individual
blog publisher or a hired blogger).

Have a look at my web-site :: Travel Blog

Hello to all, the contents present at this website are in fact remarkable for people experience,well,
keep up the nice work fellows.

Feel free to visit my web page :: led strip volt ()

I'm extremely impressed with your writing skills and also with the layout on your weblog.
Is this a paid theme or did you modify it yourself? Either way
keep up the excellent quality writing, it's rare to see a great blog like this
one these days.

Also visit my homepage - castle Clash hack

Yoս've made some dеcent points there. I looked on the internet for morе infօ about the issue aand
found most peoplе will go along with your views on thіs
site.

Here iis mmy page ubs Ag Indonesia

nice article, solved my problem.
Thanks

I'm not sure why but this web site is loading extremely slow for me.
Is anyone else having this issue or is it a issue on my end?
I'll check back later on and see if the problem still exists.


Visit my blog ... หีดารา twitter

Hello sir i got this error when i run the project,
Column name or number of supplied values does not match table definition.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Column name or number of supplied values does not match table definition.

Source Error:


Line 38: cmd.Parameters.AddWithValue("@Email", txtemail.Text.ToString());
Line 39: cmd.Parameters.AddWithValue("@Password", txtpassword.Text.ToString());
Line 40: cmd.ExecuteNonQuery();
Line 41: Sendemail();
Line 42: Clear();

i get this error sir,need some help
Cannot insert the value NULL into column 'User_Id'

Thanks for appreciation...keep reading for more valuable articles...

Exception Details: System.Data.SqlClient.SqlException: Column name or number of supplied values does not match table definition.

Exception Details: System.Data.SqlClient.SqlException: Column name or number of supplied values does not match table definition.

I have upload the project. Please check it out. It helps you

It didn't send the activation code on mu mail

Code is working. If you get the problem download the code and let me know error

what's that link you mention here("http://localhost:9525/Important_Testing/Verification.aspx?USER_ID=" & GetUserID(txtemail.Text))

it didn't send the link on mail nothing can be appear on my mail

This code is working on localserver through visual studio and I get verification email. When I host this page on server, code is working but I am not getting verification email. Am I missing something?

This code is working on localserver through visual studio and I get verification email. When I host this page on server, code is working but I am not getting verification email. Am I missing something?

This code is working on localserver through visual studio and I get verification email. When I host this page on server, code is working but I am not getting verification email. Am I missing something?


EmoticonEmoticon