萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 檢測 Email 郵箱是否真實存在:checkdnsrr 與 SMTP 驗證

前言

驗證 Email 格式容易,但確認郵箱「真實存在」較複雜。本文介紹三層驗證策略:格式驗證 → DNS MX 記錄查詢 → SMTP 連線驗證,並說明各層級的可靠度與限制。

第一層:格式驗證 (正則表達式)

<?php
function validateEmailFormat($email) {
    // RFC 5322 簡化版,涵蓋 99% 常見格式
    $pattern = '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/';
    return (bool)preg_match($pattern, $email);
}

// 使用 PHP 內建過濾器 (PHP 5.2+)
function validateEmailFilter($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

// 測試
$emails = ['test@example.com', 'invalid', 'user@domain', 'user.name+tag@sub.domain.com'];
foreach ($emails as $email) {
    echo "$email: " . (validateEmailFormat($email) ? '格式正確' : '格式錯誤') . "<br>";
}
?>

第二層:DNS MX 記錄查詢 (checkdnsrr)

<?php
function checkDomainMx($email) {
    // 取得域名部分
    $parts = explode('@', $email);
    if (count($parts) !== 2) return false;
    $domain = $parts[1];

    // 查詢 MX 記錄 (郵件交換記錄)
    if (checkdnsrr($domain, 'MX')) {
        return true;
    }
    
    // 部分域名無 MX 但有 A 記錄也可收信 (RFC 5321 fallback)
    if (checkdnsrr($domain, 'A')) {
        return true;
    }
    
    return false;
}

// 進階:取得所有 MX 記錄及優先序
function getMxRecords($domain) {
    $mxHosts = [];
    $weights = [];
    if (getmxrr($domain, $mxHosts, $weights)) {
        array_multisort($weights, SORT_ASC, $mxHosts);
        return array_combine($mxHosts, $weights);
    }
    return [];
}

// 測試
$domains = ['gmail.com', 'yahoo.com', 'nonexistent12345.com', 'example.com'];
foreach ($domains as $domain) {
    $mx = getMxRecords($domain);
    echo "$domain: " . ($mx ? implode(', ', array_keys($mx)) : '無 MX 記錄') . "<br>";
}
?>

第三層:SMTP 連線驗證 (最接近真實)

透過 SMTP 連線至郵件伺服器,模擬發送流程驗證帳號存在 (RCPT TO),但不實際發送郵件。

<?php
function verifyEmailSmtp($email, $timeout = 10) {
    $parts = explode('@', $email);
    if (count($parts) !== 2) return ['valid' => false, 'reason' => '格式錯誤'];
    $domain = $parts[1];

    // 取得 MX 記錄
    $mxHosts = [];
    $weights = [];
    if (!getmxrr($domain, $mxHosts, $weights)) {
        return ['valid' => false, 'reason' => '無 MX 記錄'];
    }
    array_multisort($weights, SORT_ASC, $mxHosts);

    // 依優先序嘗試連線
    foreach ($mxHosts as $mxHost) {
        $fp = @fsockopen($mxHost, 25, $errno, $errstr, $timeout);
        if (!$fp) continue;

        stream_set_timeout($fp, $timeout);
        
        // 讀取歡迎訊息
        $response = fgets($fp, 512);
        if (strpos($response, '220') !== 0) {
            fclose($fp);
            continue;
        }

        // HELO
        fwrite($fp, "HELO " . gethostname() . "\r\n");
        $response = fgets($fp, 512);
        if (strpos($response, '250') !== 0) {
            fclose($fp);
            continue;
        }

        // MAIL FROM (使用假寄件者)
        fwrite($fp, "MAIL FROM: <verify@example.com>\r\n");
        $response = fgets($fp, 512);
        if (strpos($response, '250') !== 0) {
            fclose($fp);
            continue;
        }

        // RCPT TO (關鍵驗證步驟)
        fwrite($fp, "RCPT TO: <$email>\r\n");
        $response = fgets($fp, 512);
        
        // QUIT
        fwrite($fp, "QUIT\r\n");
        fclose($fp);

        // 解析回應碼
        if (strpos($response, '250') === 0) {
            return ['valid' => true, 'reason' => 'SMTP 驗證通過', 'mx' => $mxHost];
        } elseif (strpos($response, '550') === 0) {
            return ['valid' => false, 'reason' => '郵箱不存在: ' . trim($response), 'mx' => $mxHost];
        } elseif (strpos($response, '450') === 0 || strpos($response, '451') === 0 || strpos($response, '452') === 0) {
            return ['valid' => null, 'reason' => '暫時性錯誤 (灰名單/忙碌): ' . trim($response), 'mx' => $mxHost];
        }
    }

    return ['valid' => null, 'reason' => '無法連線任何 MX 伺服器'];
}

// 使用範例
$result = verifyEmailSmtp('test@gmail.com');
echo "結果: " . json_encode($result, JSON_UNESCAPED_UNICODE);
?>

三層驗證整合類別

<?php
class EmailValidator {
    public function validate($email, $level = 2) {
        // Level 1: 格式
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return ['valid' => false, 'level' => 1, 'reason' => '格式不符'];
        }

        // Level 2: DNS MX
        if ($level >= 2) {
            $domain = explode('@', $email)[1];
            if (!checkdnsrr($domain, 'MX') && !checkdnsrr($domain, 'A')) {
                return ['valid' => false, 'level' => 2, 'reason' => '域名無郵件記錄'];
            }
        }

        // Level 3: SMTP (較慢、可能被封 IP、部分郵件商拒絕驗證)
        if ($level >= 3) {
            return $this->verifySmtp($email);
        }

        return ['valid' => true, 'level' => $level, 'reason' => '通過驗證'];
    }

    private function verifySmtp($email) {
        // ... 使用上方 verifyEmailSmtp 邏輯
        return ['valid' => null, 'level' => 3, 'reason' => 'SMTP 驗證未實作'];
    }
}

// 使用
$validator = new EmailValidator();
echo json_encode($validator->validate('test@example.com', 2), JSON_UNESCAPED_UNICODE);
?>

重要限制與法律/道德提醒

  1. 灰名單:多數主流郵件商 (Gmail, Outlook, Yahoo) 會對首次連線回應 450 暫時拒絕,需重試
  2. 反垃圾機制:頻繁驗證會導致 IP 被封鎖、列入黑名單
  3. 隱私法規:GDPR、個資法規範個人資料蒐集,驗證行為可能涉及合規風險
  4. Catch-all 域名:部分企業郵箱設定 catch-all,所有帳號都回應 250,無法確認真實存在
  5. 不建議大量批次驗證:會被視為垃圾郵件偵測行為

實務建議

  • 註冊流程:僅做格式驗證 + 發送驗證信 (雙重確認),最可靠且合規
  • 表單即時檢查:前端 HTML5 <input type="email"> + 簡單正則
  • 清洗既有名單:離線批次跑 DNS MX 篩除明顯無效域名
  • 使用第三方 API:ZeroBounce、NeverBounce、Hunter.io 等專業驗證服務 (付費但準確)
copyright © 萬盛學電腦網 all rights reserved