how to check the validity of email address

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
LVL 4
lokeshvAsked:
Who is Participating?
 
us111Connect With a Mentor Commented:
// 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
 
andreifCommented:
0
 
lokeshvAuthor Commented:
US111..

its not showing error in invalid usernames ...

but yeah show the invalid domain names error...


any idea ?



Lk
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
us111Commented:
hmm are you sure?
give me an email you'd like to test or send it to us111box@hotmail.com
0
 
andreifCommented:
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
 
us111Commented:
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
 
Richard QuadlingSenior Software DeveloperCommented:
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
 
us111Commented:
heeh good question! I believe it's more easier to use sockets under Unix rather than Windows
0
 
Richard QuadlingSenior Software DeveloperCommented:
And for the stupido here, how do you use that class?

Richard.
0
 
us111Commented:
?
include ("email_validation.php.inc");

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

$test->ValidateEmailBox("euiqwziurzewz@yahoo.com");
?>
0
 
Richard QuadlingSenior Software DeveloperCommented:
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
 
us111Commented:
:( yep

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

us111

so any other suggestion to do this ?

JAVA,pearl anything ?


project of $800 :o(


Lk


0
 
us111Commented:
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
 
Richard QuadlingSenior Software DeveloperCommented:
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
 
Richard QuadlingSenior Software DeveloperCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.