German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


How to Validate & Verify Users Emails and generate an automatic password?

Written by omerkamal on Feb 28, 2007
Validation and Verification possibilities of an email in ASP .NET 2.0

Explanation:

In online registration its always a tedious mechanism to determin that if enterd email was correct or not.
Here we are talking about  to different processes.

  1. Email Validation
  2. Email Verification

For Email Validation we can use the expression Validator. Select Email type in the Expression type in the Expression Validator ASP .NET 2.0 Control. This will match the enterd Email with an Expression.
We can also create our own Validator by using Javascript(for cleint side validation) or C#(for server side validation) and Regex Class.

public static bool IsEmail(string Email)
    {
        string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
            @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
            @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
        Regex re = new Regex(strRegex);
        if (re.IsMatch(Email))
            return (true);
        else
            return (false);
    } 

For Email Verification we can use three different methods:

  1. SMTP Network connection and Handshake
  2. MX records Cheking
  3. Sending an automatically generated code/Password

SMTP Network connection and Handshake

First we will check that if the domain is valid. The following code will through an exepsion if the domain name does not exist.

string[] host = (address.Split('@'));
string hostname = host[1];
    
IPHostEntry IPhst = Dns.Resolve(hostname);
IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0], 25);
Socket s= new Socket(endPt.AddressFamily,
        SocketType.Stream,ProtocolType.Tcp);
s.Connect(endPt);

Now, when we are sure that the domain name exist, we can do handshake with the Mail server and see if the email exist or not.

private enum SMTPResponse: int
{
CONNECT_SUCCESS = 220,
GENERIC_SUCCESS = 250,
DATA_SUCCESS = 354,
QUIT_SUCCESS = 221
}
private bool CanHandshake(){
if(!Check_Response(s, SMTPResponse.CONNECT_SUCCESS))
{
s.Close();
return false;
}

Senddata(s, string.Format("HELO {0}\r\n", Dns.GetHostName() ));
if(!Check_Response(s, SMTPResponse.GENERIC_SUCCESS))
{
s.Close();
return false;
}

Senddata(s, string.Format("MAIL From: {0}\r\n", message.From ));
if(!Check_Response(s, SMTPResponse.GENERIC_SUCCESS))
{
s.Close();
return false;
}


Check the MX Records
There is a better way (and also expensive) to do Email verification.We can use ASPMX tool for this activity. This tool checks the MX Records in distanation Email server.
I my self still could not figure out how can we do this through .NET platform. If some one knows then please write in the comments.
Of course, not every body can afford this Tool to buy as the Licence is a bit expensive. This is why we have to see some other way.

Sending a Verification code or an automatically generated password
1st way would be which most websites use, is to create and send a verification code to the newly registerd user and only activate the user when he enterd the right code.

2nd way which is I preferd to use, is to create an automatically generated password (instead of verification code) which the user can only use, when he can get in the email in his inbox.
The presedence which I found in the later was that you dont need to creat extra database record system. That is, if you want that the user enter verification code you have to save the code in a Table which will later let the system match both codes. The disadvantage code be that if the user enterd wrong email he wont be able to access the Account any more and you will get an inactive user in the users list. To minimize this activity, alert or inform the user that if email is enterd wrong then he/she wont be able to use the account.

In both cases you need a snippet which help you create a piece of code. To create automatic password you can use the Membership object.

The method signature look like this:

public static string GeneratePassword ( int length, int numberOfNonAlphanumericCharacters )


A practicale usage would be the following example code:

public void CreateUser_OnClick(object sender, EventArgs args)
{
  // Generate a new 12-character password with 1 non-alphanumeric character.
  string password = Membership.GeneratePassword(12, 1);

  try
  {
    // Create new user.

    MembershipUser newUser = Membership.CreateUser(UsernameTextbox.Text, password,
                                                   EmailTextbox.Text);

    Msg.Text = "User " + Server.HtmlEncode(UsernameTextbox.Text) + " created. " +
               "Your temporary password is " + password + ".";
  }
  catch (MembershipCreateUserException e)
  {
    Msg.Text = GetErrorMessage(e.StatusCode);
  }
  catch (HttpException e)
  {
    Msg.Text = e.Message;
  }
}
public string GetErrorMessage(MembershipCreateStatus status)
{
   switch (status)
   {
      case MembershipCreateStatus.DuplicateUserName:
        return "Username already exists. Please enter a different user name.";

      case MembershipCreateStatus.DuplicateEmail:
        return "A username for that e-mail address already exists. Please enter a different e-mail address.";

      case MembershipCreateStatus.InvalidPassword:
        return "The password provided is invalid. Please enter a valid password value.";

      case MembershipCreateStatus.InvalidEmail:
        return "The e-mail address provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.InvalidAnswer:
        return "The password retrieval answer provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.InvalidQuestion:
        return "The password retrieval question provided is invalid. Please check the value and try again.";

      caseMembershipCreateStatus.ProviderError:
       return"The authentication provider returned an error. Please verify your entry and try again.";

      case MembershipCreateStatus.UserRejected:
        return"The user creation request has been canceled. Please verify your entry and try again.";

      default:
       return "An unknown error occurred. Please verify your entry and try again.";
   }
}


I tried the above built-in Membership Password generation method but for reasons it did work for me when I tried to use no NonAlphaNumeric Characters. This is why I had to create my own simple function like this:

private string GenerateFriendlyPassword(int intPasswordLength)
{
// add any more characters that you wish!
string strChars = "abcdefghijklmnopqrstuvwxyz1234567890";
Random r = new Random();
string strNewPassword = string.Empty;
for (int i = 0; i < intPasswordLength; i++)
{
int intRandom = r.Next(0, strChars.Length);
strNewPassword += strChars[intRandom];
}
return strNewPassword;
}


Visitors/Readers Comments
(for questions please use The Forum)



Jegan

cool!

ok bye

22/06/2007 14:35:10 UTC

John
I'd like to get my hands on a free version of ASPMX or a bit of guidence as to how I could do it myself

18/09/2007 04:03:34 UTC

tester
javascript:alert('Hello');

08/01/2008 05:01:25 UTC

Boss
Good peice of code...

05/02/2008 03:49:19 UTC

Gopi
Thanku friend ! this key generation is useful for me
Thank u

28/06/2008 06:46:38 UTC

murthy
I tried the above built-in Membership Password generation method but for reasons it did work for me when I tried to use no NonAlphaNumeric Characters. This is why I had to create my own simple function like this:

04/09/2008 23:58:40 UTC

murthy

Thanku friend ! this key generation is useful for me
Thank u

05/09/2008 00:00:08 UTC

murthy
we are all checked the main things of the dog

08/09/2008 03:03:14 UTC

Lokesh

Its very nice.

08/09/2008 03:03:43 UTC

murthy
https://dotnet-friends.com/articles/asp/artinasp37fcd130-d299-41c5-ac29-7e9f40187d6e.aspx

08/09/2008 03:06:50 UTC

Lokesh
Thank you

08/09/2008 04:03:22 UTC




Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)