Solved

how to check the validity of email address

Posted on 2002-05-06
16
936 Views
Last Modified: 2007-12-19
how can i check the given email address is valid email address ?


 (no format checking wann to know excatly the mailbox exists on mail server)


Thnaks in advance..

Lk
0
Comment
Question by:lokeshv
  • 7
  • 5
  • 2
  • +1
16 Comments
 
LVL 6

Expert Comment

by:andreif
ID: 6991112
0
 
LVL 8

Accepted Solution

by:
us111 earned 100 total points
ID: 6993268
// This function takes in an email address
 // and tests to see if it's a valid email address.
 //  
 // An array with the results is passed back to the caller.  
 //  
 // Possible result codes for the array items are:  
 //  
 // Item 0: [true|false]    true for valid email address  
 //          false for NON-valid email address  
 //  
 // Item 1: [SMTP Code]    if a valid MX mail server found, then
 //          fill this array in with failed SMTP  
 //          reply codes  
 //  
 // Item 2: [true|false]    true for valid mail server found for  
 //          host/domain  
 //          false if no valid mail server found  
 //  
 // Item 3: [MX server]    if a valid MX host was found and  
 //          connected to then fill in this item  
 //          with the MX server hostname  
 //

function validateEmail($email)  
{      $debug_=0;
    // used for SMTP HELO argument  
         global $SERVER_NAME;  

        // initialize our return array, populating with default values  
         $return = array ( false,  "",  "",  "" );  
   
       // assign our user part and domain parts respectively to seperate       // variables

         list ( $user, $domain ) = split (  "@", $email, 2 );  
         if($debug_==1)
      {       echo "user: $user<BR>";  
           echo "domain: $domain<BR>";  
         }
    // split up the domain name into sub-parts  
         $arr = explode (  ".", $domain );  

    // figure out how many parts to the host/domain name portion there are  
         $count = count ( $arr );  

    // get our Top-Level Domain portion (i.e. foobar.org)  
         $tld = $arr[$count - 2] .  "." . $arr[$count - 1];  

    // check that an MX record exists for Top-Level Domain, and if so  
    // start our email address checking  
         if ( checkdnsrr ( $domain,  "MX" ) )  
         {      if($debug_==1) {
             echo "Check DNS RR OK<BR>";
    }
    // Okay...valid dns reverse record; test that MX record for  
    // host exists, and then fill the 'mxhosts' and 'weight'  
    // arrays with the correct information  
    if ( getmxrr ( $domain, $mxhosts, $weight ) )  
    {      if($debug_==1)
            {      echo  "MX LOOKUP RESULTS :<BR>";
               for ( $i = 0; $i < count ( $mxhosts ); $i++ )
                  {      echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;o $mxhosts[$i]<BR>";
               }
             }

        // sift through the 'mxhosts' connecting to each host  
             for ( $i = 0; $i < count ( $mxhosts ); $i++ )  
             {       
         
             // open socket on port 25 to mxhosts, setting
            // returned file pointer to the variable 'fp'

        $fp = fsockopen ( $mxhosts[$i], 25 );  
        // if the 'fp' was set, then goto work  
        if ($fp)  
           {      if($debug_==1)
                     {      echo "Socket Opened successfully<BR>";
                 }
            // work variables  
                 $s = 0;  
                 $c = 0;  
                 $out =  "";  
     
            // set our created socket for 'fp' to    
            // non-blocking mode  
            // so our fgets() calls will return  
            // right away  
                 set_socket_blocking ( $fp, false );  

            // as long as our 'out' variable has a  
            // null value ("")  
            // keep looping (do) until we get  
            // something  
            //  
                 do  
                 {      // output of the stream assigned  
                    // to 'out' variable  
                   $out = fgets ( $fp, 2500 );  
                   if($debug_==1)
                        {       if($out !=  "") echo "out: $out<BR>";
                   }
                    // if we get an "220" code (service ready code (i.e greeting))  
                    // increment our work (code (c)) variable, and null  
                    // out our output variable for a later loop test  
                   if ( ereg (  "^220", $out ) )  
                  {      if($debug_==1)
                               {      echo "service ready on recipient machine.<BR>";
                           }
                           $s = 0;  
                           $out =  "";  
                           $c++;  
                           $return[2] = true;  
                           $return[3] = $mxhosts[$i];  
                   }  
                   // elseif c is greater than 0  
                   // and 'out' is null (""),  
                   // we got a code back from some  
                   // server, and we've passed  
                   // through this loop at least  
                   // once  
                   else if (($c > 0) && ($out ==  ""))  
                   {      if($debug_==1)
                               {      echo "OK so far Breaking...<BR>";
                          }
                           $return[2] = true;  
                           break;  
                   }  
                   // else increment our 's'  
                   // counter  
                   else  
                   {       $s++;        }  
                   // and if 's' is 9999, break, to  
                   // keep from looping  
                   // infinetly  
                   if ( $s == 9999 )
                         {      if($debug_==1)
                               {      echo "Reached maximum 10000 loops, breaking.<BR>";
                           }    
                           break;  
                   }       
                 } while ( $out ==  "" );  

                 // reset our file pointer to blocking  
                 // mode, so we wait  
                 // for communication to finish before  
                 // moving on...  
                   set_socket_blocking ( $fp, true );  

                 // talk to the MX mail server,  
                 // validating ourself (HELO)  
                 fputs ( $fp,  "HELO $SERVER_NAME\n" );  
                 if($debug_==1)
                     {       echo "<BR><BR>HELO $SERVER_NAME<BR>";
                   }
                  // get the mail servers reply, assign to  
                 // 'output' (ignored)  
                 $output = fgets ( $fp, 2000 );  
           
                // give a bogus "MAIL FROM:" header to  
                // the server  
                 fputs ( $fp,  "MAIL FROM: <info@" . $domain .  ">\n" );  
                 if($debug_==1)
                     {      echo "MAIL FROM: &lt;info@" . $domain .  "&gt;<BR>";
                 }
                 // get output again (ignored)  
                 $output = fgets ( $fp, 2000 );  

                 // give RCPT TO: header for the email  
                 // address we are testing  
                 fputs ( $fp,  "RCPT TO: <$email>\n" );        
                 if($debug_==1)
                     {      echo "RCPT TO: &lt;$email&gt;<BR>";
                 }
                 // get final output for validity testing  
                 // (used)  
                 $output = fgets ( $fp, 2000 );
                 if($debug_==1)
                     {      echo "output : $output<BR>";
                 }  
                 // test the reply code from the mail  
                 // server for the 250 (okay) code  
                 if ( ereg (  "^250", $output ) )  
                 {      if($debug_==1) {
                   echo "Recipiant OK<BR>";
                 }
                 // set our true/false(ness)  
                 // array item for testing  
              $return[0] = true;  
               }  
        else  
        {      // otherwise, bogus address,  
            // fillin the 2nd array item  
            // with the mail servers reply  
            // code for user to test if they  
            // want  
            $return[0] = false;  
            $return[1] = $output;  
            if($debug==1)
                  {      echo "Bad Recipiant <BR>";
            }
             }  
         
        // tell the mail server we are done  
        // talking to it  
        fputs ( $fp,  "QUIT\n" );  
        if($debug==1)
            {      echo "Quit";
        }
        // close the file pointer  
        fclose( $fp );  

        // if we got a good value break,  
        // otherwise, we'll keep  
        // trying MX records until we get a good  
        // value, or we  
        // exhaust our possible MX servers  
        if ($return[0] == true)
            {      if($debug_==1)
                  {      echo "Recipiant OK... Breaking";
            }    
            break;  
        }  
           }  
        }  
     }  
         }
         else
         {      // No MX record appears for the specified Top-Level Domain; possibly  
          // an invalid host/domain name was specified.  
           $return[0] = false;  
           $return[1] =  "Invalid email address (bad domain name)";  
           $return[2] = false;  
         }  // end if checkdnsrr()  

         // return the array for the user to test against  
      return $return;
}
?>
0
 
LVL 4

Author Comment

by:lokeshv
ID: 6993640
US111..

its not showing error in invalid usernames ...

but yeah show the invalid domain names error...


any idea ?



Lk
0
 
LVL 8

Expert Comment

by:us111
ID: 6993744
hmm are you sure?
give me an email you'd like to test or send it to us111box@hotmail.com
0
 
LVL 6

Expert Comment

by:andreif
ID: 6993829
I can say that last stage check (SMTP) does not provide 100%  guarantee that email is correct. But it's the best that can be done. Problem is that SMTP servers are really different. The only way to verify email is send a message with code and ask to reply or follow the link.
0
 
LVL 8

Expert Comment

by:us111
ID: 6993899
yeah, I've just testing with the address you provided me.
It looks that yahoo.com always answer true. So........

you can also try with the following code, but the answer will be the same

<?
/*
 * email_validation.php
 *
 * @(#) $Header: /cvsroot/PHPlibrary/email_validation.php,v 1.6 2000/06/13 02:20:38 mlemos Exp $
 *
 */

class email_validation_class
{
 var $email_regular_expression="^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,4}\$";
 var $timeout=0;
 var $localhost="";
 var $localuser="";
 var $debug=0;

 Function OutputDebug($message)
 {
  echo $message,"\n";
 }

 Function GetLine($connection)
 {
  for($line="";;)
  {
   if(feof($connection))
    return(0);
   $line.=fgets($connection,100);
   $length=strlen($line);
   if($length>=2
   && substr($line,$length-2,2)=="\r\n")
   {
    $line=substr($line,0,$length-2);
    if($this->debug)
     $this->OutputDebug("< $line");
    return($line);
   }
  }
 }

 Function PutLine($connection,$line)
 {
  if($this->debug)
   $this->OutputDebug("> $line");
  return(fputs($connection,"$line\r\n"));
 }

 Function ValidateEmailAddress($email)
 {
  return(eregi($this->email_regular_expression,$email)!=0);
 }

 Function ValidateEmailHost($email,$hosts=0)
 {
  if(!$this->ValidateEmailAddress($email))
   return(0);
  $user=strtok($email,"@");
  $domain=strtok("");
  if(GetMXRR($domain,&$hosts,&$weights))
  {
   $mxhosts=array();
   for($host=0;$host<count($hosts);$host++)
    $mxhosts[$weights[$host]]=$hosts[$host];
   KSort($mxhosts);
   for(Reset($mxhosts),$host=0;$host<count($mxhosts);Next($mxhosts),$host++)
    $hosts[$host]=$mxhosts[Key($mxhosts)];
  }
  else
  {
   $hosts=array();
   if(strcmp(@gethostbyname($domain),$domain)!=0)
    $hosts[]=$domain;
  }
  return(count($hosts)!=0);
 }

 Function VerifyResultLines($connection,$code)
 {
  while(($line=$this->GetLine($connection)))
  {
   if(!strcmp(strtok($line," "),$code))
    return(1);
   if(strcmp(strtok($line,"-"),$code))
    return(0);
  }
  return(-1);
 }

 Function ValidateEmailBox($email)
 {
  if(!$this->ValidateEmailHost($email,&$hosts))
   return(0);
  if(!strcmp($localhost=$this->localhost,"")
  && !strcmp($localhost=getenv("SERVER_NAME"),"")
  && !strcmp($localhost=getenv("HOST"),""))
     $localhost="localhost";
  if(!strcmp($localuser=$this->localuser,"")
  && !strcmp($localuser=getenv("USERNAME"),"")
  && !strcmp($localuser=getenv("USER"),""))
     $localuser="root";
  for($host=0;$host<count($hosts);$host++)
  {
   if($this->debug)
    $this->OutputDebug("Connecting to host \"".$hosts[$host]."\"...");
   if(($connection=($this->timeout ? fsockopen($hosts[$host],25,&$errno,&$error,$this->timeout) : fsockopen($hosts[$host],25))))
   {
    if($this->debug)
     $this->OutputDebug("Connected.");
    if($this->VerifyResultLines($connection,"220")>0
    && $this->PutLine($connection,"HELO $localhost")
    && $this->VerifyResultLines($connection,"250")>0
    && $this->PutLine($connection,"MAIL FROM: <$localuser@$localhost>")
    && $this->VerifyResultLines($connection,"250")>0
    && $this->PutLine($connection,"RCPT TO: <$email>")
    && ($result=$this->VerifyResultLines($connection,"250"))>=0)
    {
     if($this->debug)
      $this->OutputDebug("This host states that the address is ".($result ? "" : "not ")."valid.");
     fclose($connection);
     if($this->debug)
      $this->OutputDebug("Disconnected.");
     return($result);
    }
    if($this->debug)
     $this->OutputDebug("Unable to validate the address with this host.");
    fclose($connection);
    if($this->debug)
     $this->OutputDebug("Disconnected.");
   }
   else
   {
    if($this->debug)
     $this->OutputDebug("Failed.");
   }
   
  }
  return(-1);
 }
};

?>
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 6993943
OOI, does anyone know of any plans to port the checkdsnrr() function to the Windows platform? Or for what reason this has not already been done?

Richard.
0
 
LVL 8

Expert Comment

by:us111
ID: 6993955
heeh good question! I believe it's more easier to use sockets under Unix rather than Windows
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 40

Expert Comment

by:RQuadling
ID: 6993973
And for the stupido here, how do you use that class?

Richard.
0
 
LVL 8

Expert Comment

by:us111
ID: 6993992
?
include ("email_validation.php.inc");

$test = new email_validation_class;
$test->debug = 1;

$test->ValidateEmailBox("euiqwziurzewz@yahoo.com");
?>
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 6994007
Damn and blast!

GetMXRR is not supported under windows either.

So. This would be telling me that you cannot validate an email address on Windows.

Ho hum!

Richard.
0
 
LVL 8

Expert Comment

by:us111
ID: 6994021
:( yep

from the PHP site:
Warning, Neither function : getmxrr() and checkdnsrr() is supported in the Win32 build of PHP..........
0
 
LVL 4

Author Comment

by:lokeshv
ID: 6994046
hmm..

us111

so any other suggestion to do this ?

JAVA,pearl anything ?


project of $800 :o(


Lk


0
 
LVL 8

Expert Comment

by:us111
ID: 6994079
I don't think that another language will solve the problem.
Besides, some mail server are protected by firewall.

I tried with yahoo.com by using telnet on port 25, some commands are blocked, so..........
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 6994120
I know you want to validate email address, but you do you want to do this?

If it is to authenticate the user, then I would send an email saying that this address has been added and if it is to be used then reply to it via a web address with a return code.

As long as the code is random, it cannot be guessed.

I think this is about as "authenticated" as you can get. I've noticed that more and more secure sites are not allowing the webmail addresses (yahoo, hotmail, etc), as there is easy way to authenticate these addresses.

Regards,

Richard Quadling.
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 10350835
And I would personally like to take the time to apologies for the appaling grammer and spelling and plain stupidness of my last comment!

What is the world coming to. Wouldn't happen in my day!

Regards,

Richard 'old man' Quadling.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now