Page 1 of 1

ASP.NET C# How to Generate A Random Password And Email It To Someone

#1 mb2000inc  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 21
  • View blog
  • Posts: 333
  • Joined: 10-November 09

Posted 01 September 2011 - 11:52 AM

Hello! Welcome to another exciting tutorial (and yes, it's very exciting - well, for me, anyway).

So, I keep getting asked - here and on other sites, how to generate random characters - say, for creating a new password or creating a unique identifier - or just because you want to generate random characters for no specific reason, but to have them at your disposal. So, I started looking around and didn't really find anything here - or on the other sites that I belong to. With that in mind, I created this simple example on how to generate the random password - and email it to someone.

It's a simple process and I hope you find it helpful.

SO! Essentially what I did, first, was create a "public string" called "GeneratePassword()" and had it return a value that I called later in my project.

While, yes it is true, that I COULD do this all in one function... but where's the fun in that? For this tutorial, it also shows how to call one thing into another.

Also, please note that I do realize that this is not the only way to do it... it's just one way that I thought would be easy for most people.

    public string GeneratePassword()
    {
       //Since I'm big on security, I wanted to generate passwords that contained numbers, letters and special
       //characters - and not easily hacked.

        //I started with creating three string variables.
        //This one tells you how many characters the string will contain.
        string PasswordLength = "12";
        //This one, is empty for now - but will ultimately hold the finised randomly generated password
        string NewPassword = "";

        //This one tells you which characters are allowed in this new password
        string allowedChars = "";			
        allowedChars = "1,2,3,4,5,6,7,8,9,0";	
        allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";
        allowedChars += "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
        allowedChars += "~,!,@,#,$,%,^,&,*,+,?";

        //Then working with an array...

        char[] sep = { ',' };
        string[] arr = allowedChars.Split(sep);

        string IDString = "";
        string temp = "";

        //utilize the "random" class
        Random rand = new Random();	

        //and lastly - loop through the generation process...
        for (int i = 0; i < Convert.ToInt32(PasswordLength); i++)
        {
            temp = arr[rand.Next(0, arr.Length)];
            IDString += temp;
            NewPassword = IDString;

            //For Testing purposes, I used a label on the front end to show me the generated password.
            //lblProduct.Text = IDString;
        }

        return NewPassword;
    }



Now, let's take this to the next step and have it sent to someone who just forgot their password and needs it reset.
For the sake of argument, there's a form on this website where a user had to put in some information and their email address... and just clicked the "Send New Password" button.

Here's the code-behind:
protected void btnSendPassword_Click(object sender, EventArgs e)
    {
        //create your variables
        string strSubject = "Your Password Has Been Reset";
        string strFromEmail =  "me@mywebsite.com";
        string strFromName = "My Website Administrator";
        string strNewPassword = GeneratePassword().ToString();  //This is where you'd call the new password string.

        try
        {
            //create the new mail message[/color]
            MailMessage MailMsg = new MailMessage();

            //cretate the FROM[/color]
            MailMsg.From = new MailAddress(strFromEmail);

            //create the subject[/color]
            MailMsg.Subject = strSubject;

            //We obviously need to create the TO - otherwise it goes nowhere.
            MailMsg.To.Add(txtEmail.Text); //assuming there was a form to fill out and they put the right email address in.

            MailMsg.IsBodyHtml = true; //I decided to make it html - so I could format the text.
            MailMsg.Body = "<h1>The following email was sent to you by " + strFromName + ".</h1><br />";
            MailMsg.Body += "<p>Apparently, you needed your password reset - So here it is: <br />";
            MailMsg.Body += "New Password <b>" + strNewPassword + "</b><br />";
            MailMsg.Body += "If you didn't request this, then - oops, you might wanna think about changing it, now. "</b>";
            MailMsg.Body += "<p>Click the following link to change your password:</p>";
            MailMsg.Body += "<p>http://www.mywebsite.com/passwordChangeThing/Default.aspx</P>";

            //utilizing SMTP (simple mail transfer protocol)
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "email.mywebsite.com"; //if my domain had a way of sending out emails.
            smtp.Send(MailMsg);  //send it

            lblMessage.Text = "Message Sent Successfully";  //tell the person that the email was sent.

        }
        catch (Exception ex)
        {
            lblMessage.Text = "Error: " + ex.ToString();  //or tell the person that they screwed up and it's all their fault.... or what the actual error was.
        }
    }



That's it. Enjoy! If this tutorial was helpful in any way, and you thought it was good, then I was happy to do it.
Please feel free to leave comments at the bottom and, even boost my reputation.

If not, than please tell me ("nicely") that you hated it and never want me to do another one as long as I live under penalty of Bobo the Clown - King of the Underworld, where no amount of peanut M&M's will get me out of there.

Have a great day! :)

Is This A Good Question/Topic? 1
  • +

Replies To: ASP.NET C# How to Generate A Random Password And Email It To Someone

#2 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4437
  • View blog
  • Posts: 7,713
  • Joined: 08-June 10

Posted 08 September 2011 - 10:50 AM

Just a quick note:

Quote

string strNewPassword = GeneratePassword().ToString();


Calling .ToString on something that is already a string is unnecessary. So it can be skipped.
Was This Post Helpful? 2
  • +
  • -

#3 mb2000inc  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 21
  • View blog
  • Posts: 333
  • Joined: 10-November 09

Posted 08 September 2011 - 11:15 AM

Heh, good point. Thanks for the input. :)
Was This Post Helpful? 0
  • +
  • -

#4 NurulH  Icon User is offline

  • New D.I.C Head

Reputation: 7
  • View blog
  • Posts: 16
  • Joined: 18-January 11

Posted 08 September 2011 - 04:09 PM

View Postmb2000inc, on 01 September 2011 - 11:52 AM, said:

string PasswordLength = "12";
Convert.ToInt32(PasswordLength);


Good writing. The cast won't be necessary if you declared PasswordLength as type int. Just saving a bit you know :wink:
Was This Post Helpful? 1
  • +
  • -

#5 mb2000inc  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 21
  • View blog
  • Posts: 333
  • Joined: 10-November 09

Posted 08 September 2011 - 05:20 PM

Another excellent point, thanks for your input. :)
Was This Post Helpful? 0
  • +
  • -

#6 Gavisann  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 103
  • View blog
  • Posts: 382
  • Joined: 01-July 11

Posted 08 September 2011 - 05:25 PM

Good job for your first tutorial. Keep up the good work.
Was This Post Helpful? 0
  • +
  • -

#7 mb2000inc  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 21
  • View blog
  • Posts: 333
  • Joined: 10-November 09

Posted 08 September 2011 - 08:06 PM

Thanks, if I can manage a few more projects, I might have a fee more tutorials coming up...
Was This Post Helpful? 0
  • +
  • -

#8 aspjava  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 14-January 12

Posted 14 January 2012 - 02:12 AM

thanks for your post
but there is another simplest way to generate random words as password with use of Guid method in asp.net and c#

String RandomWord = Guid.NewGuid().ToString();

it generates a long word with "-" and chars and numbers
you can customize it with some methods .
for example for having a random word with 12 chars and without "-" you can extend it like this

String RandomWord = Guid.NewGuid().ToString().Replace("-","").Substring(0,12);

with Best wishes
Persian Programmers
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1