如何使用 PHP 按域验证电子邮件地址?

How to validate email address by domain using PHP?

我想使用 php 验证电子邮件域,因为一些用户试图使用虚拟电子邮件 ID 提交联系表单,例如:aa@bb.com

如果您只想验证域名部分的语法,您可以将电子邮件拆分为 @ 和 运行 第二部分的正则表达式(在 运行ning 之后它通过 idn_to_ascii() 国际域名功能):

/
    ^
    (?(DEFINE)(?<part>(?:xn--)?[a-z\d](?:[a-z\d-]*[a-z\d])?))
    (?(DEFINE)(?<subpart>(?:xn--)?[a-z\d_](?:[a-z\d_-]*[a-z\d])?))
    (?:(?&subpart)\.)*
    (?&part)
    (?:\.[a-z]+|\.xn--[a-z\d]+){1,2}
    $
/xigm

https://regex101.com/library/PAKVdK

您需要检查该域是否有 MX 记录。

除了正则表达式验证之外,请考虑使用此脚本

https://davidwalsh.name/php-email-validator

请注意,这不会 'really' 完全验证电子邮件。用户可能无效。

尝试 checkdnsrr 从电子邮件地址中提取域名并传递给 checkdnsrr。

Returns TRUE if domain name are found; returns FALSE if no domain name were found or if an error occurred.

$domainname = "domain.com";

checkdnsrr($domainname , "A");

如果您不想自己完成验证的所有麻烦,只需使用 MailboxValidator 中的 free API plan

他们有一些示例代码可以帮助您进行集成。

http://www.mailboxvalidator.com/api-single-validation

<?php
$apiKey = 'Enter_License_Key';
$params['format']           = 'json';
$params['email']     = 'Enter_Email';

$query = '';

foreach($params as $key=>$value){
    $query .= '&' . $key . '=' . rawurlencode($value);
}

$try = 0;
do {
    ////////////
    //For https request, please make sure you have enabled php_openssl.dll extension.
    //
    //How to enable https
    //- Uncomment ;extension=php_openssl.dll by removing the semicolon in your php.ini, and restart the apache.
    //
    //In case you have difficulty to modify the php.ini, you can always make the http request instead of https.
    ////////////
    $result = file_get_contents('https://api.mailboxvalidator.com/v1/validation/single?key=' . $apiKey . $query);
} while(!$result && $rty++ < 3);

$data = json_decode($result);

print_r($data);
?>