Generating Random Password and mail it to the user emailid.


In this article i am explaning the logic for creating random password and mail it to the user. If the user forgets his/her password then we can use this logic of generating random password for sending him the new password by emailid.

You all must have observed this many times in your day to day activities that when we forget our passwords and want to generate a new one the website automatically sends a randomly generated password on our email id. I would here be providing you with a code snippet for randomly generating passwords and emailing it to user's email id automatically.

The steps of execution would be as follows:
1. First we will check whether the User with the supplied username exist or not.
2. If user exist we will read its detail like name,username and emailid from the table.
3. Then we will generate the random password.
4. At last we will send the password to the emailid of the user.

Below is the codes for all the steps:


protected void btnforget_Click(object sender, EventArgs e)
{
string username = txtUser.Text.Trim();
string connection = ConfigurationManager.ConnectionStrings["HospitalConnectionString"].ToString();
int newid;
SqlConnection con = new SqlConnection(connection);

// IsValidUser is the stored procedure which will check whether user with the specific username exist or not.

SqlCommand command = new SqlCommand("IsValidUser", con);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@UserName", System.Data.SqlDbType.VarChar, 100)).Value = username;
command.Parameters.Add(new SqlParameter("@UserID", System.Data.SqlDbType.Int, 4)).Direction = System.Data.ParameterDirection.Output;
try
{
con.Open();
command.ExecuteNonQuery();
newid = (int)command.Parameters["@UserID"].Value;
if (newid == 1)
{
command = new SqlCommand("SELECT * FROM User_Info WHERE UserName='" + username + "'", con);
SqlDataReader reader;
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
int UserId = Convert.ToInt32(reader["Id"]);
string FirstName = reader["FirstName"].ToString();
string LastName = reader["LastName"].ToString();
string EmailId = reader["EmailId"].ToString();
string UserName = reader["UserName"].ToString();
/*CreateRandomPassword() method will genearte the randow password.*/

string password = CreateRandomPassword(8);

//UPdatePassword() method will update the password in the database.

UPdatePassword(UserId, FirstName, LastName, EmailId, username, password);
}
reader.Close();
}
}
else if (newid == -1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Invalid User : ", "<SCRIPT LANGUAGE='javascript'>alert('User De-activated');</script>", false);
}
else
{
btnLogin.Enabled = true;
ClearControls();
txtLoginId.Focus();
ScriptManager.RegisterStartupScript(this, this.GetType(), "Invalid User : ", "<SCRIPT LANGUAGE='javascript'>alert('Invalid User');</script>", false);
}
}
catch (Exception ex)
{
//trace error
string log = ex.Message;
}
finally
{
con.Close();
}
}

private void UPdatePassword(int UserId, string FirstName, string LastName, string EmailId, string username, string password)
{
string connection = ConfigurationManager.ConnectionStrings["HospitalConnectionString"].ToString();

string sql = "UPDATE User_Info SET Password = @password WHERE id=" + UserId + "";
SqlConnection con = new SqlConnection(connection);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlParameter[] pram = new SqlParameter[1];
pram[0] = new SqlParameter("@password", SqlDbType.VarChar, 50);
pram[0].Value = password;
for (int i = 0; i < pram.Length; i++)
{
cmd.Parameters.Add(pram[i]);
}
cmd.ExecuteNonQuery();

//////////////////////////////////////email code/////////////////////////////////////////
MailMessage MyMailMessage = new MailMessage();
MyMailMessage.From = new MailAddress("hospital.care12@gmail.com", "donotreply");//mail id and display name

MyMailMessage.To.Add(EmailId);
MyMailMessage.Subject = "Login Credentials";
MyMailMessage.IsBodyHtml = true;

string body = "Hi " + Fname + "," + Lname + "
Your Credentials are as follows:
Username: " + UserName + "
Password: " + password + "";

MyMailMessage.Body = body;

System.Net.Mail.SmtpClient SMTPServer = new SmtpClient("smtp.gmail.com");
SMTPServer.Port = 587;
SMTPServer.Credentials = new System.Net.NetworkCredential("hospital.care12@gmail.com", "care@12");//mail id and password
SMTPServer.EnableSsl = true;
try
{
SMTPServer.Send(MyMailMessage);
lblstatus.Visible = true;
lblstatus.Text = " Credentials has been sent to your account. please check.";
}
catch (Exception ex)
{
lblstatus.Text = "Unable to send mail.";
}
}

private string CreateRandomPassword(int PasswordLength)
{
string _allowedChars = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
Random randNum = new Random();
char[] chars = new char[PasswordLength];
int allowedCharCount = _allowedChars.Length;
for (int i = 0; i < PasswordLength; i++)
{
chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
}
return new string(chars);
}


Below is the table structure:

CREATE TABLE [dbo].[User_Info](
[id] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NULL,
[UserName] [varchar](100) NOT NULL,
[Phone] [varchar](50) NOT NULL,
[Password] [varchar](100) NULL,
[EmailId] [varchar](50) NOT NULL,
[RoleId] [varchar](50) NULL,
[UserTheme] [varchar](50) NULL,
[LastLoginDate] [varchar](50) NULL,
[IsLoggedIn] [bit] NULL,
[IsActive] [bit] NULL
) ON [PRIMARY]


Following the Code of "IsValidUser" Stored procedure.

CREATE PROCEDURE [dbo].[IsValidUser]
@UserName [varchar](100),
@UserID [int] OUTPUT
WITH EXECUTE AS CALLER
AS
BEGIN

IF EXISTS (SELECT * FROM User_Info WHERE Username = @UserName AND IsActive = 1)
BEGIN
SET @UserID = 1
END
ELSE
IF EXISTS (SELECT * FROM User_Info WHERE Username = @UserName AND IsActive = 0)
BEGIN
SET @UserID = -1
END
ELSE
BEGIN
SET @UserID = 0
END
END


Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: