Welcome to W3Courses
 Like Us on Facebook

How to check if an email address exists without sending an email?

We have all been doing email address validation for a very long time to make sure that the email is correctly formatted. This is to avoid users entering wrongly formatted email address but still they can accidentally give us a wrong email address.

Example of a correctly formatted email address but still wrong:

mailbox.does.not.exist@reddit.com [VALID email fromat but still not correct]

Above case specifically happens when you take important customer email on phone and you type in the wrong email. So is there a QUICK solution to really check the email without sending a test message to the user? Yes.

The solution

A quick & simple check below can be implemented in most programming language including PHP, Python etc. It relies on using the same SMTP which is used to send emails.

To check if user entered email mailbox.does.not.exist@reddit.com really exists go through the following in command prompt.

First - Find mail exchanger of reddit.com

COMMAND:
nslookup – q=mx reddit.com
RESPONSE:
reddit.com      MX preference = 10, mail exchanger = mail.reddit.com
mail.reddit.com internet address = 208.96.53.70

Second - Connect to mail server mail.reddit.com

COMMAND:
telnet mail.reddit.com 25
RESPONSE:
220 mail.reddit.com ESMTP Postfix NO UCE NO UEMA  C=US L=CA Unsolicated electronic mail advertisements strictly prohibited, subject to fine under CA law CBPC 17538.45.  This electronic mail service provider’s equipment is located in the State of California.  See http://www.reddit.com/static/inbound-email-policy.html for more information.

COMMAND:
helo hi
RESPONSE:
250 mail.reddit.com

COMMAND:
mail from: <youremail@gmail.com>
RESPONSE:
250 2.1.0 Ok

COMMAND:
rcpt to: <mailbox.does.not.exist@reddit.com>
RESPONSE:
550 5.1.1 <mailbox.does.not.exist@reddit.com>: Recipient address rejected: User unknown in local recipient table

COMMAND:
quit
RESPONSE:
221 2.0.0 Bye

NOTES:

1) the 550 response indicates that the email address is not valid and you have caught a valid but wrong email address. This code can be on the server and called on AJAX when user tabs out of the email field.  The entire check will take less than 2 seconds to run and you can make sure that the email is correct.
2) If email was present the server will respond with a 250 instead of 550
3) There are certain servers with a CATCH ALL email and this means all email address are accepted as valid on their servers (RARE but some servers do have this setting).
4) Please do not use this method to continuously to check for availability of gmail / yahoo / msn accounts etc as this may cause your IP to be added to a blacklist.
5) This is to supplement the standard email address javascript validation.

SMTP Check Code in PHP

<?php 
  
 /**
 * Validate Email Addresses Via SMTP
 * This queries the SMTP server to see if the email address is accepted.
 * @copyright http://creativecommons.org/licenses/by/2.0/ - Please keep this comment intact
 * @author gabe@fijiwebdesign.com
 * @contributers adnan@barakatdesigns.net
 * @version 0.1a
 */ 
class SMTP_validateEmail { 
 
 /**
  * PHP Socket resource to remote MTA
  * @var resource $sock 
  */ 
 var $sock; 
 
 /**
  * Current User being validated
  */ 
 var $user; 
 /**
  * Current domain where user is being validated
  */ 
 var $domain; 
 /**
  * List of domains to validate users on
  */ 
 var $domains; 
 /**
  * SMTP Port
  */ 
 var $port = 25; 
 /**
  * Maximum Connection Time to an MTA 
  */ 
 var $max_conn_time = 30; 
 /**
  * Maximum time to read from socket
  */ 
 var $max_read_time = 5; 
  
 /**
  * username of sender
  */ 
 var $from_user = 'user'; 
 /**
  * Host Name of sender
  */ 
 var $from_domain = 'localhost'; 
  
 /**
  * Nameservers to use when make DNS query for MX entries
  * @var Array $nameservers 
  */ 
 var $nameservers = array( 
 '192.168.0.1' 
); 
  
 var $debug = false; 
 
 /**
  * Initializes the Class
  * @return SMTP_validateEmail Instance
  * @param $email Array[optional] List of Emails to Validate
  * @param $sender String[optional] Email of validator
  */ 
 function SMTP_validateEmail($emails = false, $sender = false) { 
  if ($emails) { 
   $this->setEmails($emails); 
  } 
  if ($sender) { 
   $this->setSenderEmail($sender); 
  } 
 } 
  
 function _parseEmail($email) { 
  $parts = explode('@', $email); 
 $domain = array_pop($parts); 
 $user= implode('@', $parts); 
 return array($user, $domain); 
 } 
  
 /**
  * Set the Emails to validate
  * @param $emails Array List of Emails
  */ 
 function setEmails($emails) { 
  foreach($emails as $email) { 
  list($user, $domain) = $this->_parseEmail($email); 
  if (!isset($this->domains[$domain])) { 
    $this->domains[$domain] = array(); 
  } 
  $this->domains[$domain][] = $user; 
 } 
 } 
  
 /**
  * Set the Email of the sender/validator
  * @param $email String
  */ 
 function setSenderEmail($email) { 
 $parts = $this->_parseEmail($email); 
 $this->from_user = $parts[0]; 
 $this->from_domain = $parts[1]; 
 } 
  
 /**
 * Validate Email Addresses
 * @param String $emails Emails to validate (recipient emails)
 * @param String $sender Sender's Email
 * @return Array Associative List of Emails and their validation results
 */ 
 function validate($emails = false, $sender = false) { 
   
  $results = array(); 
 
  if ($emails) { 
   $this->setEmails($emails); 
  } 
  if ($sender) { 
   $this->setSenderEmail($sender); 
  } 
 
  // query the MTAs on each Domain 
  foreach($this->domains as $domain=>$users) { 
    
  $mxs = array(); 
   
   // retrieve SMTP Server via MX query on domain 
   list($hosts, $mxweights) = $this->queryMX($domain); 
 
   // retrieve MX priorities 
   for($n=0; $n < count($hosts); $n++){ 
    $mxs[$hosts[$n]] = $mxweights[$n]; 
   } 
   asort($mxs); 
  
   // last fallback is the original domain 
   array_push($mxs, $this->domain); 
    
   $this->debug(print_r($mxs, 1)); 
    
   $timeout = $this->max_conn_time/count($hosts); 
     
   // try each host 
   while(list($host) = each($mxs)) { 
    // connect to SMTP server 
    $this->debug("try $host:$this->port\n"); 
    if ($this->sock = fsockopen($host, $this->port, $errno, $errstr, (float) $timeout)) { 
     stream_set_timeout($this->sock, $this->max_read_time); 
     break; 
    } 
   } 
   
   // did we get a TCP socket 
   if ($this->sock) { 
    $reply = fread($this->sock, 2082); 
    $this->debug("<<<\n$reply"); 
     
    preg_match('/^([0-9]{3}) /ims', $reply, $matches); 
    $code = isset($matches[1]) ? $matches[1] : ''; 
  
    if($code != '220') { 
     // MTA gave an error... 
     foreach($users as $user) { 
      $results[$user.'@'.$domain] = false; 
  } 
  continue; 
    } 
 
    // say helo 
    $this->send("HELO ".$this->from_domain); 
    // tell of sender 
    $this->send("MAIL FROM: <".$this->from_user.'@'.$this->from_domain.">"); 
     
    // ask for each recepient on this domain 
    foreach($users as $user) { 
     
     // ask of recepient 
     $reply = $this->send("RCPT TO: <".$user.'@'.$domain.">"); 
      
      // get code and msg from response 
     preg_match('/^([0-9]{3}) /ims', $reply, $matches); 
     $code = isset($matches[1]) ? $matches[1] : ''; 
   
     if ($code == '250') { 
      // you received 250 so the email address was accepted 
      $results[$user.'@'.$domain] = true; 
     } elseif ($code == '451' || $code == '452') { 
   // you received 451 so the email address was greylisted (or some temporary error occured on the MTA) - so assume is ok 
   $results[$user.'@'.$domain] = true; 
     } else { 
      $results[$user.'@'.$domain] = false; 
     } 
     
    } 
     
    // quit 
    $this->send("quit"); 
    // close socket 
    fclose($this->sock); 
    
   } 
  } 
 return $results; 
 } 
 
 
 function send($msg) { 
  fwrite($this->sock, $msg."\r\n"); 
 
  $reply = fread($this->sock, 2082); 
 
  $this->debug(">>>\n$msg\n"); 
  $this->debug("<<<\n$reply"); 
   
  return $reply; 
 } 
  
 /**
  * Query DNS server for MX entries
  * @return 
  */ 
 function queryMX($domain) { 
  $hosts = array(); 
 $mxweights = array(); 
  if (function_exists('getmxrr')) { 
   getmxrr($domain, $hosts, $mxweights); 
  } else { 
   // windows, we need Net_DNS 
  require_once 'Net/DNS.php'; 
 
  $resolver = new Net_DNS_Resolver(); 
  $resolver->debug = $this->debug; 
  // nameservers to query 
  $resolver->nameservers = $this->nameservers; 
  $resp = $resolver->query($domain, 'MX'); 
  if ($resp) { 
   foreach($resp->answer as $answer) { 
    $hosts[] = $answer->exchange; 
    $mxweights[] = $answer->preference; 
   } 
  } 
   
  } 
 return array($hosts, $mxweights); 
 } 
  
 /**
  * Simple function to replicate PHP 5 behaviour. http://php.net/microtime
  */ 
 function microtime_float() { 
  list($usec, $sec) = explode(" ", microtime()); 
  return ((float)$usec + (float)$sec); 
 } 
 
 function debug($str) { 
  if ($this->debug) { 
   echo htmlentities($str); 
  } 
 } 
 

 
  
?>
 

Usage Example

<?php

// the email to validate  
$email = 'joe@gmail.com';  
// an optional sender  
$sender = 'user@example.com';  
// instantiate the class  
$SMTP_Valid = new SMTP_validateEmail();  
// do the validation  
$result = $SMTP_Valid->validate($email, $sender);  
// view results  
var_dump($result);  
echo $email.' is '.($result ? 'valid' : 'invalid')."\n";  
  
// send email?   
if ($result) {  
  //mail(...);  
}

?>  

Share