php实现接收邮件
使用 IMAP 扩展接收邮件
PHP 内置的 IMAP 扩展可以连接邮件服务器并获取邮件内容。确保服务器已安装 IMAP 扩展(php.ini 中启用 extension=imap)。
连接邮件服务器并获取收件箱列表:
$mailbox = '{imap.example.com:993/imap/ssl}INBOX';
$username = 'your_email@example.com';
$password = 'your_password';
$inbox = imap_open($mailbox, $username, $password);
$emails = imap_search($inbox, 'ALL');
遍历邮件并解析内容:

if ($emails) {
rsort($emails);
foreach ($emails as $email_number) {
$header = imap_headerinfo($inbox, $email_number);
$body = imap_body($inbox, $email_number);
echo "Subject: " . $header->subject . "\n";
echo "From: " . $header->fromaddress . "\n";
}
}
imap_close($inbox);
使用 PHPMailer 库接收邮件
PHPMailer 主要用于发送邮件,但可通过结合 IMAP 功能实现接收。安装 PHPMailer:
composer require phpmailer/phpmailer
示例代码与原生 IMAP 类似,需配合 IMAP 函数使用:

require 'vendor/autoload.php';
$mailbox = new PHPMailer\PHPMailer\PHPMailer();
// 实际仍需使用 imap_* 函数操作
解析邮件内容
邮件内容可能为纯文本或 HTML,需根据需要进行处理:
$structure = imap_fetchstructure($inbox, $email_number);
if ($structure->parts) {
foreach ($structure->parts as $part) {
$body = imap_fetchbody($inbox, $email_number, $part->partnumber);
if ($part->encoding == 3) {
$body = imap_base64($body);
}
}
}
处理附件
检查邮件是否包含附件并保存:
if (isset($structure->parts) && count($structure->parts) > 1) {
for ($i = 1; $i < count($structure->parts); $i++) {
$attachment = imap_fetchbody($inbox, $email_number, $i+1);
file_put_contents("attachment_$i.dat", $attachment);
}
}
安全注意事项
- 使用 SSL/TLS 加密连接(端口 993)。
- 避免硬编码密码,改用环境变量或配置文件。
- 对邮件内容进行过滤,防止 XSS 或注入攻击。
替代方案:第三方 API
对于不支持 IMAP 的服务,可使用如 Gmail API 等第三方接口:
// 需配置 OAuth 和 API 密钥
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$service = new Google_Service_Gmail($client);
$messages = $service->users_messages->listUsersMessages('me');






