Password Reminder: Reset the password and send it to the user's provided mail address

Utsav
Posted by in ASP.NET category on for Intermediate level | Views : 7842 red flag
Rating: 4 out of 5  
 1 vote(s)

After learning this tutorial, you will be able to generate a random password and send it to the user's requested mail address.
Introduction
This is a tutorial to how to make password reminder page in your application. It first takes the username and email address input from the User  and then checks whether the username exit or not then generates the random password and then mails the reset password to the user's mail address.

Database
Design the table named as Users and provide the following column as shown in the diagram.
 




Design Page Passwordreminder.aspx
Now its time to design your page which looks as:


..and the coding for the above output goes here:

PasswordReminder.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div style="left:15px; position:absolute; top:20px;">
Enter Your UserName and EmailID to reset your password..
</div>

<div style="left:15px; position:absolute; top:60px;">
<asp:Label ID="lblUserName" runat="server" Text="User Name"></asp:Label>
</div>

<div style="left:110px; position:absolute; top:60px;">
<asp:TextBox ID="txtuserName" runat="server"></asp:TextBox>
</div>

<div style="left:15px; position:absolute; top:100px;">
<asp:Label ID="lblEmail" runat="server" Text="Email Address"></asp:Label>
</div>

<div style="left:110px; position:absolute; top:100px;">
<asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
</div>

<div style="left:200px; position:absolute; top:140px;">
<asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
Text="Submit" />
</div>

<div style="left:15px; position:absolute; top:200px;">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</div>



</form>
</body>
</html>




  Now the coding section for the PasswordReminder.aspx.cs :

public partial class PasswordReminder : System.Web.UI.Page
{
public char[] chars = new char[6]; // Stores the newly generated passwords.
public static bool flag = false;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{

checkUsername(); // Function checks whether the username exist or not
if (flag == true)
{
resetPass(); // Function resets the password of current username
sendMail(); // Function sends the newly generated password to the User's mail
// address
}
else
{
lblMessage.Text = "Please provide the correct Username !";
}

}

  Above we can see after the submit button is clicked it fires the btnSubmit_Click() function.

Now lets view the coding for the function checkUsername()

 protected void checkUsername()
{
string username = txtuserName.Text;
string connStr = ConfigurationManager.ConnectionStrings["UsersString"].ToString();

SqlConnection conn = new SqlConnection(connStr);
SqlCommand dCmd = new SqlCommand("SELECT * FROM Users", conn);

SqlDataReader reader;

try
{
conn.Open();

reader = dCmd.ExecuteReader();

while (reader.Read())
{
string dbusername = reader["UserName"].ToString();

if (username.Equals(dbusername))
{
flag = true;
break;
}


}
}
catch(Exception ee)
{
lblMessage.Text = ee.Message.ToString();

}
finally
{
dCmd.Dispose();
conn.Close();
}
}

       The above function checks whether the Username exist or not. If the Username exist then publicly defined boolean variable flag is set to true. but if not then the flag is still false. Afer this function executes then the flag is checked whether it is false or true.
If the flag is false then the Output: "Please provide the correct username !" is generated(cause username does not exist in the database)
       If Username exists then the resetPass() and sendMail() function executes which generates the 6 digit random password and sends to the user's mail address correspondingly.

Here the connectionstring for my database i used as : UsersString. My Webconfig files looks as below:

<connectionStrings>

  <add name="UsersString" connectionString="Data    Source=DataSource1 ;Initial Catalog=YourProjectName;Integrated Security=True;Pooling=False user id=SampleUser; password=SampleUser;"

   providerName="System.Data.SqlClient" />

</connectionStrings>

The remaining function resetPass() and sendMail() goes here:

resetPass() :

protected void resetPass()

    {

        string username = txtuserName.Text;

   string connStr = ConfigurationManager.ConnectionStrings["UsersString"].ToString();


        SqlConnection conn = new SqlConnection(connStr);

        SqlCommand dCmd = new SqlCommand("UPDATE Users SET Password = @passWord WHERE UserName = '" + username + "' ", conn);

        dCmd.CommandType = CommandType.Text;

        conn.Open();

        try

        {

            int PasswordLength = 6;

            string allowedchars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";

            Random randNum = new Random();

            int allowedCharCount = allowedchars.Length;



            for (int i = 0; i < PasswordLength; i++)

            {

                chars[i] = allowedchars[(int)((allowedchars.Length) * randNum.NextDouble())];



            }

           string newpass = new string(chars);

           dCmd.Parameters.AddWithValue("@passWord", newpass);

           dCmd.ExecuteNonQuery();

           

        }

        catch (Exception ee)

        {

            lblMessage.Text = ee.Message.ToString();

        }

        finally

        {

            dCmd.Dispose();

            conn.Close();

        }
  }

 

sendMail() : 

protected void sendMail()
{

string newpass = new string(chars);

string email = txtemail.Text;
string from = "Yourmail@serverdomain.com";

try
{

MailMessage mMailmessage = new MailMessage();

mMailmessage.From = new MailAddress(from);

mMailmessage.To.Add(new MailAddress(email));

mMailmessage.Subject = "noreply";

mMailmessage.Body = "Your Password is:" + newpass + "";


// Set the format of the mail message body as HTML

mMailmessage.IsBodyHtml = true;


mMailmessage.BodyEncoding = System.Text.Encoding.ASCII;


SmtpClient mSmtpClient = new SmtpClient();

mSmtpClient.Host = "YourMailserverName";



mSmtpClient.Port = 25;


mSmtpClient.Send(mMailmessage);

mMailmessage.Dispose();
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}

}

You have to set your mailsettings in webconfig file before using the mail function.

<system.net>
<mailSettings>
<smtp from="Yourmail@serverdomain.com">

<network host="YourMailserverName" port="25" userName="" password="" />
</smtp>

</mailSettings>

</system.net>
Conclusion:
Thus this tutorial teaches how to generate the password randomly and send it to the specified Username.


Page copy protected against web site content infringement by Copyscape

About the Author

Utsav
Full Name: Utsav Pokhrel
Member Level: Starter
Member Status: Member
Member Since: 6/17/2009 9:09:11 AM
Country: Nepal
Regards, Utsav Pokhrel
http://www.uts-chupakabras.blogspot.com

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)