From time to time you will need to check if an email is valid before sending actual messages to it. This can be used when you register people to your site and so on.
This simple PHP function will do it but do keep in mind this is not 100% bulletproof. Yahoo reported me a mailbox as valid but later got a reply with undeliverable message: mailbox did not exist.
But, in most cases, this script will work and will help you validate mailboxes easily.
Here is the code,
//—————————————————————————-
function verifyMailbox($email,$mailAddress=“no-reply@no-mail.com”) {
$before = microtime();
$err = false;
if (!preg_match(‘/([^\@]+)\@(.+)$/’, $email, $matches)) {
return false;
}
$user = $matches[1]; $domain = $matches[2];
if(!function_exists(‘checkdnsrr’)) return $err;
if(!function_exists(‘getmxrr’)) return $err;
// Get MX Records to find smtp servers handling this domain
if(getmxrr($domain, $mxhosts, $mxweight)) {
for($i=0;$i<count($mxhosts);$i++){
$mxs[$mxhosts[$i]] = $mxweight[$i];
}
asort($mxs);
$mailers = array_keys($mxs);
}elseif(checkdnsrr($domain, ‘A’)) {
$mailers[0] = gethostbyname($domain);
}else {
return false;
}
// Try to send to each mailserver
$total = count($mailers);
$ok = 0;
for($n=0; $n < $total; $n++) {
$timeout = 5;
$errno = 0; $errstr = 0;
if(!($sock = fsockopen($mailers[$n], 25, $errno , $errstr, $timeout))) {
continue;
}
$response = fgets($sock);
stream_set_timeout($sock, 5);
$meta = stream_get_meta_data($sock);
$cmds = array(
“HELO localhost”,
“MAIL FROM: <$mailAddress>”,
“RCPT TO: <$email>”,
“QUIT”,
);
if(!$meta['timed_out'] && !preg_match(‘/^2\d\d[ -]/’, $response)) {
break;
}
$success_ok = 1;
foreach($cmds as $cmd) {
fputs($sock, “$cmd\r\n”);
$response = fgets($sock, 4096);
if(!$meta['timed_out'] && preg_match(‘/^5\d\d[ -]/’, $response)) {
$success_ok = 0;
break;
}
}
fclose($sock);
if($success_ok){
$ok = 1;
break;
}
}
$after = microtime();
// Fail on error
if(!$ok) return false;
// Return a positive value on success
return $after-$before;
}
//—————————————————————————-
its not working in windows server
ReplyDelete