Can't remember where I got this from, but has been tweaked slightly. This is for a unix box only but can be modified to run under windows.
This is very heavy on the network, as it will check the host to ensure it is correct by opening a socket to it too to ensure the domain is all OK.
function ValidateMail($Email) {
$HTTP_HOST = $_SERVER['HTTP_HOST'];
$result = array();
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $Email))
{
$result[0]=false;
$result[1]="The email address is not properly formatted";
return $result;
}
list ( $Username, $Domain ) = split ("@",$Email);
$mxs = getmxrr($Domain, $MXHost);
if (count($mxs)>0)
{
$ConnectAddress = $mxs[0];
}
else
{
$ConnectAddress = $Domain;
}
@$Connect = fsockopen ( $ConnectAddress, 25 );
if ($Connect)
{
if (ereg("^220", $Out = fgets($Connect, 1024)))
{
fputs ($Connect, "HELO $HTTP_HOST\r\n");
$Out = fgets ( $Connect, 1024 );
fputs ($Connect, "MAIL FROM: <".$Email.">\r\n");
$From = fgets ( $Connect, 1024 );
fputs ($Connect, "RCPT TO: <".$Email.">\r\n");
$To = fgets ($Connect, 1024);
fputs ($Connect, "QUIT\r\n");
fclose($Connect);
if (!ereg ("^250", $From) || !ereg ( "^250", $To )) {
$result[0]=false;
$result[1]="Server rejected address ";
return $result;
}
}
else
{
$result[0] = false;
$result[1] = "No response from server";
return $result;
}
}
else
{
$result[0]=false;
$result[1]="Can not connect E-Mail server.";
return $result;
}
$result[0]=true;
$result[1]="$Email appears to be valid.";
return $result;
} // end of function }
To have this run on windows box, because the getmxrr function is not there for windows, have this as another function too.
function getmxrr($hostname, &$mxhosts)
{
$mxhosts = array();
exec('%SYSTEMROOT%\\system32\\nslookup.exe -q=mx '.$hostname.' enterdnsiphere', $result_arr);
foreach($result_arr as $line)
{
if (preg_match("/.*mail exchanger = (.*)/", $line, $matches))
$mxhosts[] = $matches[1];
}
return $mxhosts;
}//--End of workaround
Sorry - usage
$email = ValidateEmail($emailaddy);
if ($email[0]==0)
{
echo $email[1];
}
else
{
//all ok so carry on
}