Click here to Skip to main content
Licence CPOL
First Posted 10 Oct 2003
Views 453,496
Bookmarked 159 times

Effective Email Address Validation

By Vasudevan Deepak Kumar | 20 Dec 2003
In this article, we would discuss a very brief and overall technique to verify the email addresses of the users that signup for a web account.
26 votes, 36.1%
1
7 votes, 9.7%
2
5 votes, 6.9%
3
8 votes, 11.1%
4
26 votes, 36.1%
5
3.14/5 - 72 votes
μ 3.11, σa 3.12 [?]

Introduction

Email has become a necessary and inseparable part of our day-to-day life. Even in the web applications we develop, the primary mode of information exchange between the website/application and the user is the email address. For this, some sites have a primary email and a secondary email (if something fails in primary, the information to be communicated to the user would be sent to the secondary address).

In any web portal and/or applications, where a diversified set of users are expected to visit and register, care should be taken, in validating the email address, since this is being intended to serve as the primary medium of contact between the user and the website.

What we cover

Sections of contents in this article are covered and researched highly in C#. But that's not all. An in-depth overview and real investigation of the email addresses, before it is saved as a primary contact of the user that is registering with the website, is needed. And that remains the objective of this article.

We would cover not only a real validation of addresses, but also some subtopics and associated topics like Password Recovery etc.

Since the topic is in general and to facilitate even object model and database designers, I am just trying to give an example code snippet, links to some applications and also about how to achieve it in different language implementations.

Validations

A very preliminary validation of email addresses is by analyzing the pattern of addresses. That is absolutely straight forward and we can define a regular expression to get the job done.

The following regular expression method in C#, would tell you, if the passed email address is syntactically valid or not. Note that, this verifies only syntactical validity and not whether the email address exists or not.

public static bool isEmail(string inputEmail)
{
   inputEmail  = NulltoString(inputEmail);
   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(inputEmail))
    return (true);
   else
    return (false);
}

The next level of validation, we can attempt is to make a negotiation with the SMTP server and validate. Some mail servers respond even to VRFY and/or RCPT SMTP commands as to whether the email address is valid or not. But servers which are very strictly configured of not disclosing non-existing addresses, will always acknowledge any junk addresses in their domain and would bounce them on their own later. We need to tackle each of the following.

Validating via SMTP Network Connection

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);

This step will throw an exception, if the domain is not valid, so that you can flag that the email address is invalid.

Validating via SMTP Handshakes

If the domain was okay, we can try to handshake with the actual server and find out whether the email address is valid or not. Perhaps, at this point, I would like to suggest the way an application used to negotiate to a SMTP server similar to how Peter has explained here (EggHeadCafe). We would not need the entire block of code anyway.

We can check each section of the SMTP negotiation like MAIL FROM and RCPT TO and optionally VRFY SMTP commands.

If from domains or from addresses are prohibited or not in the SMTP server's allow list, MAIL FROM may fail. Mail servers which allow VRFY command will let you understand whether the email address is valid or not.

My CodeSection

Since we had a similar requirement, the EggHeadCafe was really useful and I would like to share the code snippet for other users, who might be having a similar requirement.

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);

//Attempting to connect
if(!Check_Response(s, SMTPResponse.CONNECT_SUCCESS))
{                
    s.Close();
    return false;
}

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

//Identify yourself
//Servers may resolve your domain and check whether 
//you are listed in BlackLists etc.
Senddata(s, string.Format("MAIL From: {0}\r\n", 
     "testexample@deepak.portland.co.uk"));
if(!Check_Response(s, SMTPResponse.GENERIC_SUCCESS))
{
    s.Close();
    return false;
}


//Attempt Delivery (I can use VRFY, but most 
//SMTP servers only disable it for security reasons)
Senddata(s, address);
if(!Check_Response(s, SMTPResponse.GENERIC_SUCCESS))
{
    s.Close();
    return false;
}
return (true);

Check_Response, SendData are available in the original source code and you can download it from there. But you may need to read through the associated license agreement, regarding retaining copyright notices in your code. Since this is just a code snippet to introduce you to the idea, only relevant code area are being mentioned.

Temporary Validation

All goes well, if network conditions are ok. But there may be temporary network problems preventing connections. If you expect that your host may be slow, then you can send a dummy link to the email address and activate the account only if the user goes to the address and clicks the link. Otherwise, you can stop the account activation step, periodically reclaiming junk accounts by having a scheduled task in your web application.

Associated SubTopics

We were mentioning at the start of the article, that we would also cover in brief about subtopics. One such is the password recovery. But I think this article is getting too long, I am just compiling more information and would submit to you as a separate article, since it has its own configurations and limitations and may not fully apply within Email Validations.

To Summarize...

In fact, I hope a lot of web developers would be in need of similar validation routines, to ensure that the email addresses are valid and I really hope that the above hints would be helpful to them. Thanks Peter, your article really helped me and I hope your article and whatever hints I have been learning, which I have shared above, would really help more developers having similar requirements to solve.

License

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

About the Author

Vasudevan Deepak Kumar

Web Developer

India India

Member
Vasudevan Deepak Kumar is from Chennai, India who has been in the programming career since 1994, when he was 15 years old. He has his Bachelors of Engineering (in Computer Science and Engineering) from Vellore Engineering College (now VIT University). He also has a MBA in Systems from Alagappa University, Karaikudi, India.


He started his programming career with GWBasic and then in his college was involved in developing programs in Fortran, Cobol, C++. He has been developing in Microsoft technologies like ASP, SQLServer 2000. For sometime, he has also been with PHP and MySQL based development in one of his previous organizations. Now currently his focus is on Microsoft .NET World (ASP.NET, C# and Whidbey)


In his past-time, he listens to polite Carnatic Music.

Web Presence


Homepage

http://www.lavanyadeepak.tk/

Blogs



Technical




Gossips



Spiritual







Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Suggestion!Check Responce Code snippet Pinmembernobuhle.mnguni@gmail.com1:28 28 Oct '11  
GeneralMy vote of 1 PinmemberNate_112:48 1 Aug '11  
QuestionMy short and accurate regex for emails Pinmemberrhyous16:35 31 Jul '11  
Generalplease send me download link of email verification PinmemberChintanParikh21:59 26 Apr '11  
GeneralEmail Validation Pinmemberneerajgupta.8420017:51 10 Jan '11  
GeneralMy vote of 1 PinmemberRich O.5:01 22 Dec '10  
GeneralMy vote of 2 PinmemberHenry.Ayoola23:03 16 Dec '10  
QuestionMissing link to Source Code? PinmemberRanch Camal8:36 4 Nov '10  
GeneralMy vote of 5 Pinmemberpradipgh22:00 26 Jul '10  
GeneralMy vote of 1 Pinmemberwilson2good19:49 3 Jun '10  
GeneralEmail verification not working for me PinmemberNajmul Hoda21:24 5 May '10  
GeneralMy vote of 1 PinmemberTringXRay4:17 13 Apr '10  
GeneralDoes not validate emails such as john.h.smith@somewhere.com Pinmembervossjck5:26 23 Feb '10  
GeneralRe: Does not validate emails such as john.h.smith@somewhere.com PinmemberEfran Cobisi8:41 2 Mar '10  
GeneralEmail validation with ' Pinmemberleeky__18:05 12 Jan '10  
AnswerRe: Email validation with ' PinmemberEfran Cobisi8:38 2 Mar '10  
QuestionError while validating domain in emailaddress Pinmemberbala_vimal20:40 21 Jul '09  
AnswerRe: Error while validating domain in emailaddress Pinmemberorcunberkem6:41 19 Jul '10  
QuestionWhere can i get the source code? Pinmembermrgrundh0:48 1 Jul '09  
AnswerRe: Where can i get the source code? PinmemberJunior Mayhe13:37 18 Feb '10  
Generaloriginal source code Pinmemberxccx23:28 29 Apr '09  
QuestionFor other domains - not working PinmemberVarunPrakash1:09 17 Apr '09  
QuestionRe: For other domains - not working Pinmemberrose794:36 17 Jul '09  
AnswerRe: For other domains - not working PinmemberVarunPrakash7:48 17 Jul '09  
QuestionRe: For other domains - not working Pinmemberrose792:54 20 Jul '09  

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

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120209.1 | Last Updated 21 Dec 2003
Article Copyright 2003 by Vasudevan Deepak Kumar
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid