Skip to content

Instantly share code, notes, and snippets.

@maxbanton
Created August 4, 2014 13:58
Show Gist options
  • Save maxbanton/06b7de2ec221c92dc9d3 to your computer and use it in GitHub Desktop.
Save maxbanton/06b7de2ec221c92dc9d3 to your computer and use it in GitHub Desktop.
Check email addresses through SMTP
<?php
class SmtpEmailChecker
{
protected $from;
protected $code;
/**
* @return mixed
*/
public function getCode()
{
return $this->code;
}
public function __construct($from)
{
$this->from = $from;
}
public function check($email)
{
if (strpos($email, '@') === false) {
return false;
}
$mxHosts = [];
$weight = [];
getmxrr(explode('@', $email)[1], $mxHosts, $weight);
$mxHosts = array_combine($weight, $mxHosts);
ksort($mxHosts);
$socket = false;
foreach ($mxHosts as $mxHost) {
try {
$socket = fsockopen($mxHost, 25, $errno, $errstr, 5);
stream_set_timeout($socket, 5);
}
catch (Exception $e) {
}
if ($socket)
{
break;
}
}
if ($socket) {
try {
$reply = fread($socket, 2082);
$helloCode = intval(substr($reply, 0, 3));
if ($helloCode != 220) {
$this->code = 0;
return false;
}
else {
fwrite($socket, "HELO " . gethostname() . "\r\n");
fread($socket, 2082);
fwrite($socket, "MAIL FROM: <" . $this->from . ">" . "\r\n");
fread($socket, 2082);
fwrite($socket, "RCPT TO: <" . $email . ">" . "\r\n");
$response = fread($socket, 2082);
fwrite($socket, "quit" . "\r\n");
fread($socket, 2082);
fclose($socket);
$code = intval(substr($response, 0, 3));
$this->code = $code;
switch ($code) {
case 250:
return true;
case 451:
return true;
case 550:
return false;
default:
return false;
}
}
}
catch (Exception $e) {
error_log($e->getMessage());
}
}
$this->code = 0;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment