Click here to Skip to main content
15,886,810 members
Articles / Web Development
Tip/Trick

Forgot Password With Check Email From Database

Rate me:
Please Sign up or sign in to vote.
3.17/5 (5 votes)
22 Oct 2013CPOL1 min read 16.2K   124   4   8
Forgot Password and Email Check from Database

Introduction

Every registration system has a requirement but without forgot password, it's difficult to retrieve password. There is no other method through which you can access your forgotten password, so the main reason is to build a system through which users can access their forgotten passwords.

Background

Overall, it's necessary for a user if the passwords are complex and with a lot of websites in which you have an account in, you use multiple type of passwords (like add special characters or capital word including digits or any other way) according to the requirement of websites or apps. Without this, if you forget the password, you try and some websites have blockage of account after 5 to 10 tries depending on the scenario blocked for half an hour to 1 day but suppose you need it urgently, the way invented to make users relax is by giving a way to retrieve password through a link either with email or both security questions answer and email. That way, the user can easily retrieve the password in a minute or two.

Using the Code

In this tip, I am using only a simple way of retrieving password though email which you have used to register and later on for login.

First of all, add connection string in the web.config file and other app settings like key for toEmail and SmtpServer or other you would like to add define as a key in app settings and access in cs file.

XML
<!-- YOur Connection String-->
<connectionStrings>
  <add name="ForgotPassword_Connstring" connectionString="" />

</connectionStrings>
<!-- Application Settings Related to Sending Email  -->
<appSettings>
  <add key="toEmail" value=""/>
  <add key="SmtpServer" value=""/>
</appSettings>
C#
// define connection string from web.config
           string connStringforgotpassword = System.Configuration.
           ConfigurationManager.ConnectionStrings["ForgotPassword_Connstring"].ToString();
C#
string fromEmail = ConfigurationManager.AppSettings
   ["toEmail"].ToString();//    From web.config
C#
sObj.Host = ConfigurationManager.AppSettings
   ["SmtpServer"].ToString();  //    From web.config

The code of RetreivePassword.aspx page looks like this:

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

<!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>Forgot Password</title>
    <style type="text/css">
        .style1
        {
            width: 500px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center" id="wrapper">
        <br />
        <br />
        <h1>
            FORGOT PASSWORD</h1>
        <asp:Label ID="lblmessage" 
        runat="server"></asp:Label>
        <asp:TextBox ID="txtforgot" 
        runat="server" Style="width: 300px; 
        height: 30px; color: White"></asp:TextBox>
        <asp:Button ID="tbnforgot" runat="server" 
        class="login button" OnClick="tbnforgot_Click"
            Text="Forgot Pssword" CausesValidation="true" />
        <asp:RequiredFieldValidator runat="server" 
        ControlToValidate="txtforgot" Display="Dynamic"
            ForeColor="Red" SetFocusOnError="true" 
            ErrorMessage="Please enter email" 
            ID="RequiredFieldValidator1"></asp:RequiredFieldValidator>
        &nbsp;<asp:RegularExpressionValidator 
        ID="RegularExpressionValidator1" runat="server"
            ControlToValidate="txtforgot" Display="Dynamic" 
            ForeColor="Red" SetFocusOnError="True"
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
            ">Please enter valid email</asp:RegularExpressionValidator>
        <br />
    </div>
    </form>
</body>
</html>

Reference to be used in cs page is as follows:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net.Mail;
using System.Drawing; 

and for RetreivePassword.aspx.cs is:

C#
public partial class RetreivePassword : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void tbnforgot_Click(object sender, EventArgs e)
    {
        try
        {
            DataSet dsResult = new DataSet();
            // define connection string from web.config
            string connStringforgotpassword = System.Configuration.
            ConfigurationManager.ConnectionStrings["ForgotPassword_Connstring"].ToString();
            using (SqlConnection con = new SqlConnection(connStringforgotpassword))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT Email,
                Password FROM Users Where Email= '" + txtforgot.Text.Trim() + 
                "' and IsActice = 1 and Isdeleted=0", con);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dsResult);
                con.Close();
            }
            // if count of entered email matches to the above query from database then this runs 
            if (dsResult.Tables[0].Rows.Count > 0)
            {
                string fromEmail = ConfigurationManager.AppSettings
                ["toEmail"].ToString();//    From web.config            

                MailMessage mmObj = new MailMessage();
                mmObj.From = new MailAddress(fromEmail);
                mmObj.To.Add(txtforgot.Text);

                mmObj.IsBodyHtml = true;
                mmObj.Subject = "Forgot Password";
                mmObj.Body = "Hi,<br/><br />Welcome to 
                My Application <br/><br />Your UserName : " + 
                dsResult.Tables[0].Rows[0]["Email"].ToString() + " 
                and Password is : " + dsResult.Tables[0].Rows[0]
                ["Password"].ToString() + "";
                mmObj.Priority = MailPriority.High;

                SmtpClient sObj = new SmtpClient();
                System.Net.NetworkCredential myCredential = new System.Net.NetworkCredential
                ("your email (use mostly domain emails like ends 
                with .com/.net/.org e.t.c)", "your email password");
                sObj.UseDefaultCredentials = false;
                sObj.Credentials = myCredential;
                sObj.Host = ConfigurationManager.AppSettings
                ["SmtpServer"].ToString();  //    From web.config
                sObj.Port = 25;

                sObj.Send(mmObj);
                //Msg = null;
                lblmessage.Text = "Your Password Details Sent to '" + txtforgot.Text + "'";
                lblmessage.ForeColor = Color.Aqua;
                // Clear the textbox values
                txtforgot.Text = "";
            }
            else
            {
                lblmessage.Text = "The Email you entered does not 
                exist in our database. Please Enter authentic email address";
                lblmessage.ForeColor = Color.Orange;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralMy vote of 1 Pin
John B Oliver13-Nov-13 10:59
John B Oliver13-Nov-13 10:59 
GeneralMy vote of 3 Pin
jgakenhe22-Oct-13 6:49
professionaljgakenhe22-Oct-13 6:49 
GeneralMy vote of 1 Pin
vdhaeyere22-Oct-13 4:55
vdhaeyere22-Oct-13 4:55 
GeneralRe: My vote of 1 Pin
John B Oliver13-Nov-13 10:57
John B Oliver13-Nov-13 10:57 
Question[My vote of 1] Bad Practices Pin
AnalogNerd22-Oct-13 3:05
AnalogNerd22-Oct-13 3:05 
Please don't encourage people to use inline SQL and store passwords in plain text in a database. If you want to show a tip for forgotten passwords show something more secure, like how to do a single use link that is emailed to the person and would allow them to reset their password.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.