使用PHP IMAP从邮箱邮件中提取5-8位数字验证码的实现方法
PHP IMAP提取邮箱5-8位数字验证码解决方案
原有代码问题
- 仅通过
imap_fetch_overview读取邮件头部主题信息,未获取邮件正文内容,无法提取正文中的验证码 - 没有实现数字序列的匹配提取逻辑
完整修改后代码
<?php date_default_timezone_set('Asia/Ho_Chi_Minh'); error_reporting(0); // 新增:获取邮件纯文本正文的函数 function get_email_body($inbox, $email_number, $structure) { $body = ''; // 单部分邮件处理 if ($structure->type == 0) { $body = imap_fetchbody($inbox, $email_number, 1); // 编码处理:base64解码 if ($structure->encoding == 3) { $body = base64_decode($body); // quoted-printable解码 } elseif ($structure->encoding == 4) { $body = quoted_printable_decode($body); } $body = imap_utf8($body); } // 多部分邮件处理(兼容HTML+纯文本双版本、带附件的邮件) elseif ($structure->type == 1) { foreach ($structure->parts as $index => $sub_structure) { if ($sub_structure->type == 0) { // 优先取纯文本部分 $body = imap_fetchbody($inbox, $email_number, $index + 1); if ($sub_structure->encoding == 3) { $body = base64_decode($body); } elseif ($sub_structure->encoding == 4) { $body = quoted_printable_decode($body); } $body = imap_utf8($body); break; } } } return $body; } if (isset($_GET['usermail'])) { $hostname = '{imap.yandex.com:993/imap/ssl/novalidate-cert}INBOX'; $username = $_GET['usermail']; $password = $_GET['passmail']; $mail = $_GET['mail']; if ($username != "" && $password != "") { $inbox = imap_open($hostname,$username,$password) or die("Errorlogin"); $emails = imap_search($inbox,'TO "'.$mail.'"'); $output = ''; if($emails) { rsort($emails); foreach($emails as $email_number) { $structure = imap_fetchstructure($inbox, $email_number); // 获取邮件正文 $email_body = get_email_body($inbox, $email_number, $structure); // 匹配5-8位独立数字序列 if (preg_match('/\b\d{5,8}\b/', $email_body, $matches)) { $output = $matches[0]; // 找到最新邮件的验证码直接跳出,无需遍历旧邮件 break; } } if ($output) { echo "Facebook:".$output; } else { echo "nocodefound"; } } else { echo "errorinbox"; } imap_close($inbox); } else { echo "Error"; } } ?>
功能说明
- 自动适配常见邮件结构和编码格式,避免正文乱码
- 正则规则
\b\d{5,8}\b仅匹配独立的5~8位数字,不会误提取长数字中的连续片段 - 优先取最新符合条件邮件的验证码,遍历效率更高
内容的提问来源于stack exchange,提问作者Game Replay
相关产品推荐
相关产品推荐

