Skip to content

Instantly share code, notes, and snippets.

@r4v
Last active May 21, 2017 17:55
Show Gist options
  • Save r4v/bd65458cac54fddb5f19 to your computer and use it in GitHub Desktop.
Save r4v/bd65458cac54fddb5f19 to your computer and use it in GitHub Desktop.
Advanced Mail Validation
<?php
/*
* Check if given mail is valid using:
* filter_var()
* check MX record
* verify is user exist using telnet and SMPT session
*
* I'm useing this helper in ajax respone so results are echo'ed as json
*/
// CONFIG
// you should have valid SPF record for your domain, if you don't have it, some host could reject your connection
define("HELO", 'yourhost.tld'); // define your host for HELO command
define("MAIL_FROM", '<you@yourhost.tld>'); // addres used for send command MAIL FROM:
if( !function_exists('mailcheck') )
{
function mailcheck($email, $debug = FALSE)
{
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$response['valid'] = FALSE;
$response['error'] = 'syntax not valid against FILTER_VALIDATE_EMAIL';
}
else
{
$response['valid'] = TRUE;
$response['error'] = '';
}
if($response['valid'] != FALSE)
{
$host = explode('@',$email);
$dns = dns_get_record($host[1], DNS_MX);
if(empty($dns))
{
$response['valid'] = FALSE;
$response['error'] = 'no MX record for '.$host[1];
return $response;
exit;
}
$target = $dns[0]['target'];
$port = 25;
$errno = "";
$errstr = "";
$timeout = 9;
$newline = "\r\n";
$logArray = array();
$connect = fsockopen($target, $port, $errno, $errstr, $timeout);
$smtpResponse = fgets($connect, 4096);
if(empty($connect)) {
$response['valid'] = FALSE;
$response['error'] = 'can\'t connect to '.$target;
return $response;
exit;
}
fputs($connect, "HELO ". HELO . $newline);
$smtpResponse = fgets($connect, 4096);
if($debug)
{
$response['debug'][] = "CMD: HELO ". HELO. " RESPONSE: " . preg_replace('/\s+/', ' ',$smtpResponse);
}
fputs($connect, "MAIL FROM: ". MAIL_FROM . $newline);
$smtpResponse = fgets($connect, 4096);
if($debug)
{
$response['debug'][] = "CMD: MAIL FROM: ". MAIL_FROM ." RESPONSE: ".preg_replace('/\s+/', ' ',$smtpResponse);
}
fputs($connect, "RCPT TO: <".$email.">" . $newline);
$smtpResponse = fgets($connect, 4096);
if($debug)
{
$response['debug'][] = "CMD: RCPT TO: <".$email."> RESPONSE: " .preg_replace('/\s+/', ' ',$smtpResponse);
}
if(strpos($smtpResponse, '250') === FALSE )
{
$response['valid'] = FALSE;
$response['error'] = 'no such user';
if($debug)
{
$response['debug'] = preg_replace('/\s+/', ' ',$smtpResponse);
}
}
else
{
$response['valid'] = TRUE;
$response['error'] = '';
if($debug)
{
$response['debug'] = preg_replace('/\s+/', ' ',$smtpResponse);
}
}
}
return $response;
}
}
header('Content-Type: application/json');
echo json_encode(mailcheck($_GET['mail'], TRUE));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment