Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
SQL Server

How to implement forgot password functionality in ASP.NET

Author: Alanna Kremer
Download Source Code :

In this article, we will see how we can implement forgot password functionality on a login page in ASP.NET.

This article is the continuation of my previous two articles on DevASP.NET. These articles are how to create a signup page and how to create a login page. In the login page, most of the times you can see a forgot password link. This link redirects you to another page where you can see the functionality of forgot password is implemented. We have learned to create a signup page and a login page in previous articles now we need to learn forgot password functionality. The purpose of this article is to explain how this functionality is implemented.

There are different methods and approaches to implement forgot password functionality. No matter which method or approach you want to use, the basic idea is simple. You just need to ask and check the credentials of the user, check the database for password against that user id, username or email and send an email of the password to his/her email account. You can add lots of restrictions, constraints like security questions and fix number of attempts for a user when you are implementing forgot password functionality but I am going to make it simple here.
We have seen on some login pages that they use username and password to login but we have used email and password. We also know that built-in controls to create user, login user and password recovery are also available in Visual Studio toolbox but we have used our own functionality so we are choosing the same track in this article as well. We are going to use same table which we have used in signup and login pages.
Table Name: Account
Column Names: AccountID, FirstName, LastName, Email, Password, ConfirmPassword and CreateDate
Add a link of Forgot Password in Login page and redirects it to retrieve password page
Add code below in aspx page
            <td colspan="3" style="height: 21px; text-align: left">
                <span style="font-size: 12pt">Please provide following information to retrieve password
            <td style="width: 100px">
                <asp:Label ID="lblFirstName" runat="server" Text="First Name:" Width="80px"></asp:Label>
            <td style="width: 116px">
                <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
            <td style="width: 100px">
               <asp:RequiredFieldValidator ID="FirstNameRequiredFieldValidator" runat="server"
                 ForeColor="Red" ControlToValidate="txtFirstName" Display="Dynamic"
                 ErrorMessage="First Name Required" SetFocusOnError="True">*</asp:RequiredFieldValidator>
            <td style="width: 100px">
                <asp:Label ID="lblLastName" runat="server" Text="Last Name:" Width="80px"></asp:Label>
            <td style="width: 116px">
                <asp:TextBox ID="txtLastName" runat="server" ></asp:TextBox>
            <td style="width: 100px">
                 <asp:RequiredFieldValidator ID="LastNameRequiredFieldValidator" runat="server"
                   ForeColor="Red" ControlToValidate="txtLastName" Display="Dynamic"
                   ErrorMessage="Last Name Required" SetFocusOnError="True">*</asp:RequiredFieldValidator>
            <td style="width: 71px" valign="top">
                     <asp:Label ID="lblEmail" runat="server" Text="Email:">asp:Label>td>
            <td style="width: 150px; text-align: left;" valign="top">
                <asp:TextBox ID="txtEmail" runat="server" Width="225px" >asp:TextBox>td>
            <td style="width: 37px" valign="top">
                    <asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server"
                     ControlToValidate="txtEmail" Display="Dynamic" ForeColor="Red"
                     ErrorMessage="Email Required" SetFocusOnError="True</asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server"
                       ForeColor="Red" ControlToValidate="txtEmail" Display="Dynamic"
                       ErrorMessage="Provide Valid Email Address"
            <td style="width: 71px; height: 27px;"></td>
            <td style="width: 178px; text-align: right; height: 27px;">
                <asp:Button ID="btnRetrievePassword" runat="server" Style="position: relative"
                     Text="Retrieve Password" onclick="btnRetrievePassword_Click" /></td>
            <td style="width: 37px; height: 27px; text-align: right">
            <td colspan="3" style="height: 27px; text-align: center">
                <asp:ValidationSummary ID="ValidationSummary" ForeColor="Red" runat="server" />
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
Write below stored procedure to get password from database
       @FirstName           varchar(100),
       @LastName           varchar(100),
       @Email                  varchar(100)
  DECLARE @RecordCount INT
  SELECT Password
  FROM     Account
 WHERE  FirstName = @FirstName
 AND        LastName = @LastName
 AND       Email = @Email
Add following namespaces in your code behind file
using System.Data.SqlClient;
using System.Data;
using System.Net.Mail;
using System.Net;
Imports System.Data.SqlClient
Imports System.Data
Imports System.Net.Mail
Imports System.Net
Now write code below in code behind file
protected void btnRetrievePassword_Click(object sender, EventArgs e)
    string password = GetPassword(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim());
    if (password != "")
            SendEmail(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim(), password);
            lblMessage.Text = "Your password is sent to your email";
        catch (Exception ex)
            lblMessage.Text = "Sorry! an error occured while sending email, please try again";
        lblMessage.Text = "Please provide correct information";
public string GetPassword(string firstName, string lastName, string email)
    string password = "";
    string connstring = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True";
    SqlConnection conn = new SqlConnection(connstring);
    SqlCommand cmd = new SqlCommand("GetPassword", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 100).Value = firstName;
    cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 100).Value = lastName;
    cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email;
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();


        foreach (DataRow dr in dt.Rows)
            if (dr["Password"] != DBNull.Value)
                password = dr["Password"].ToString();
    catch (Exception ex)
        password = "";
    return password;
public void SendEmail(string firstname, string lastname, string email, string password)
    MailMessage emailMessage = new MailMessage("", email);
    emailMessage.Subject = "Password Recovery";
    string body = "Dear " + firstname + " " + lastname + ",<br/><br/>";
    body += "Here is your password '" + password + "'. <br/>";
    body += "Please login using your email and password. <br/><br/>";
    body += "Thank You";
    emailMessage.Body = body;
    emailMessage.IsBodyHtml = true;
    SmtpClient client = new SmtpClient();
    client.Host = "";
    client.EnableSsl = true;
    NetworkCredential NetworkCred = new NetworkCredential("YourEmail", "YourPassword");
    client.UseDefaultCredentials = true;
    client.Credentials = NetworkCred;
    client.Port = 587;
 Protected Sub btnRetrievePassword_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRetrievePassword.Click
    Dim password As String = GetPassword(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim())
    If password <> "" Then
            SendEmail(txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim(), password)
            lblMessage.Text = "Your password is sent to your email"
        Catch ex As Exception
            lblMessage.Text = "Sorry! an error occured while sending email, please try again"
        End Try
        lblMessage.Text = "Please provide correct information"
    End If
End Sub
Public Function GetPassword(ByVal firstName As String, ByVal lastName As String, ByVal email As String) As String
    Dim password As String = ""
    Dim connstring As String = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True"
    Dim conn As New SqlConnection(connstring)
    Dim cmd As New SqlCommand("GetPassword", conn)
    cmd.CommandType = CommandType.StoredProcedure
    cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 100).Value = firstName
    cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 100).Value = lastName
    cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email
        Dim adapter As New SqlDataAdapter(cmd)
        Dim dt As New DataTable()


        For Each dr As DataRow In dt.Rows
           If IsDBNull(dr("Password") = False) Then
                password = dr("Password").ToString()
           End If
           Exit For
    Catch ex As Exception
        password = ""
    End Try
    Return password
End Function
Public Sub SendEmail(ByVal firstname As String, ByVal lastname As String, ByVal email As String, ByVal password As String)
    Dim emailMessage As New MailMessage("", email)
    emailMessage.Subject = "Password Recovery"
    Dim body As String = "Dear " & firstname & " " & lastname & ",<br/><br/>"
    body += "Here is your password '" & password & "'. <br/>"
    body += "Please login using your email and password. <br/><br/>"
    body += "Thank You"
    emailMessage.Body = body
    emailMessage.IsBodyHtml = True
    Dim client As New SmtpClient()
    client.Host = ""
    client.EnableSsl = True
    Dim NetworkCred As New NetworkCredential("YourEmail", "YourPassword")
    client.UseDefaultCredentials = True
    client.Credentials = NetworkCred
    client.Port = 587
End Sub


Add Article Comment:
Name :
Email Address :
Comments :
<< How to import Gmail contacts in ASP.NET

Disclaimer - Privacy
© 2002-2017