Forgot Password By Email Page Code In Asp.Net

This Example explains how to Create Forgot Password By Email Page Code In Asp.Net Using C# And VB.NET.

I have placed one textbox and button on the ForgotPassword.aspx page to send mail to email id stored in database.

You can also send Reset Password Link instead of sending Username password in the email.

Forgot Password By Email Page In Asp.Net


HTML SOURCE OF FORGOT PASSWORD PAGE
   1:  <form id="Form1" runat="server">
   2:  <div>
   3:  <fieldset>
   4:  <legend>Forgot Password</legend> 
   5:  <asp:Label ID="lblEmail" runat="server" Text="Email Address: "/>
   6:  <asp:TextBox ID="txtEmail" runat="server"/>
   7:   
   8:  <asp:RequiredFieldValidator ID="RV1" runat="server" 
   9:                              ControlToValidate="txtEmail" 
  10:                              ErrorMessage="Please Enter EmailID" 
  11:                              SetFocusOnError="True">*
  12:  </asp:RequiredFieldValidator>
  13:   
  14:  <asp:Button ID="btnPass" runat="server" Text="Submit" 
  15:                           onclick="btnPass_Click"/>
  16:   
  17:  <asp:ValidationSummary ID="ValidationSummary1" 
  18:                         runat="server" CssClass="error"/>
  19:                         
  20:  <asp:Label ID="lblMessage" runat="server" Text=""/>
  21:  </fieldset>
  22:  </div>
  23:  </form>


Write following code in Click Event of Button to retrieve username and password associated with EmailID provided by user from database and send the information to this email id.

C# CODE
using System;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Net.Mail;

protected void btnPass_Click(object sender, EventArgs e)
    {
        //Create Connection String And SQL Statement
        string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string strSelect = "SELECT UserName,Password FROM Users WHERE Email = @Email";

        SqlConnection connection = new SqlConnection(strConnection);
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.Text;
        command.CommandText = strSelect;

        SqlParameter email = new SqlParameter("@Email", SqlDbType.VarChar, 50);
        email.Value = txtEmail.Text.Trim().ToString();
        command.Parameters.Add(email);

        //Create Dataset to store results and DataAdapter to fill Dataset 
        DataSet dsPwd = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter(command);
        connection.Open();
        dAdapter.Fill(dsPwd);
        connection.Close();
        if(dsPwd.Tables[0].Rows.Count > 0 )
        {
            MailMessage loginInfo = new MailMessage();
            loginInfo.To.Add(txtEmail.Text.ToString());
            loginInfo.From = new MailAddress("YourID@gmail.com");
            loginInfo.Subject = "Forgot Password Information";

            loginInfo.Body = "Username: " + dsPwd.Tables[0].Rows[0]["UserName"] + "

Password: " + dsPwd.Tables[0].Rows[0]["Password"] + "

"; loginInfo.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.Credentials = new System.Net.NetworkCredential("YourGmailID@gmail.com", "YourGmailPassword"); smtp.Send(loginInfo); lblMessage.Text = "Password is sent to you email id,you can now Login"; } else { lblMessage.Text = "Email Address Not Registered"; } }

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

Protected Sub btnPass_Click(sender As Object, e As EventArgs)
  'Create Connection String And SQL Statement
  Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
  Dim strSelect As String = "SELECT UserName,Password FROM Users WHERE Email = @Email"

  Dim connection As New SqlConnection(strConnection)
  Dim command As New SqlCommand()
  command.Connection = connection
  command.CommandType = CommandType.Text
  command.CommandText = strSelect

  Dim email As New SqlParameter("@Email", SqlDbType.VarChar, 50)
  email.Value = txtEmail.Text.Trim().ToString()
  command.Parameters.Add(email)

  'Create Dataset to store results and DataAdapter to fill Dataset 
  Dim dsPwd As New DataSet()
  Dim dAdapter As New SqlDataAdapter(command)
  connection.Open()
  dAdapter.Fill(dsPwd)
  connection.Close()
  If dsPwd.Tables(0).Rows.Count > 0 Then
   Dim loginInfo As New MailMessage()
   loginInfo.[To].Add(txtEmail.Text.ToString())
   loginInfo.From = New MailAddress("YourID@gmail.com")
   loginInfo.Subject = "Forgot Password Information"

   loginInfo.Body = "Username: " & Convert.ToString(dsPwd.Tables(0).Rows(0)("UserName")) & "

Password: " & Convert.ToString(dsPwd.Tables(0).Rows(0)("Password")) & "

" loginInfo.IsBodyHtml = True Dim smtp As New SmtpClient() smtp.Host = "smtp.gmail.com" smtp.Port = 587 smtp.EnableSsl = True smtp.Credentials = New System.Net.NetworkCredential("YourGmailID@gmail.com", "YourGmailPassword") smtp.Send(loginInfo) lblMessage.Text = "Password is sent to you email id,you can now Login" Else lblMessage.Text = "Email Address Not Registered" End If End Sub


Download Sample Code


If you like this post than join us or share

8 comments:

Pankaj N said...

The code is valid if the password is stored in clear text format. Most of the times it is Hashed through one way hash algorithms like SHA1. In that situation, all you can do is to send a mail with a link which has a another hash value and you ask the user to change the password on that page. That page is only usable once.
Anyway above code is a good and simple example :)


Deovrat A Sharp Spark said...

How and which SQL database has to be connected


Deovrat A Sharp Spark said...

line number 40: "..Login.aspx">Login" it says Only assignment, call, increment, decrement, and new object expressions can be used as a statement.


Unknown said...

@Pankaj: Hi, Thanks for writing, you are absolutely correct, i wrote this article for beginners to get an idea how forgot password works, i did mention, if you had not overlooked, that we can send reset password link as well, keep visiting


Unknown said...

@Deovrat A Sharp Spark : Please use single quote ' insted of double quotes in href="Login.aspx"

lblMessage.Text = "Password is sent to you email id,you can now <a href='Login.aspx'>Login</a>"


Sugan's Kitchen said...

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required


Unknown said...

i am using authentication tag for login form but the after login page is getting open via address. if i put address in address bar


mayank said...

Error:
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required


Find More Articles