You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP新手求助:使用PHPMailer发送带附件邮件失败问题

PHPMailer带附件邮件异常问题排查(Gmail收不到/附件丢失)

问题根源

  1. 手动MIME头破坏邮件结构:你手动添加了Content-type: text/html和MIME-Version头,但带附件的邮件需要multipart/mixed类型的MIME结构,强制设成text/html会让邮箱无法识别附件,甚至判定邮件格式错误直接拦截。
  2. 缺失文件上传验证:直接使用$_FILES变量,未检查文件是否上传成功(比如临时文件丢失、上传出错),无效附件会触发邮箱反垃圾机制。
  3. Gmail反垃圾策略严格:格式错误或包含无效附件的邮件极易被归为垃圾邮件拦截。

修复方案

1. 删除冲突的手动MIME头

删掉以下代码,PHPMailer会自动根据邮件内容生成正确的MIME结构:

$mail->addCustomHeader('MIME-Version', '1.0');
$mail->addCustomHeader('Content-type', 'text/html; charset=UTF-8');
$mail->ContentType = 'text/html; charset=UTF-8';

2. 强制验证文件上传状态

在添加附件前必须做上传校验,避免添加无效文件:

// 检查文件是否上传成功
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    $errorMsg = match ($_FILES['file']['error']) {
        UPLOAD_ERR_INI_SIZE => '文件超过php.ini限制大小',
        UPLOAD_ERR_FORM_SIZE => '文件超过表单限制大小',
        UPLOAD_ERR_PARTIAL => '文件仅部分上传',
        UPLOAD_ERR_NO_FILE => '未选择文件',
        default => '未知上传错误',
    };
    die($errorMsg);
}

$tmpFile = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];

// 额外确认临时文件存在
if (!file_exists($tmpFile)) {
    die('临时上传文件丢失');
}

$mail->addAttachment($tmpFile, $fileName);

3. 调试阶段开启SMTP日志

如果问题仍存在,开启调试模式查看与邮件服务器的交互日志,定位拦截原因:

$mail->SMTPDebug = SMTP::DEBUG_SERVER; // 上线前记得关闭

修改后的完整代码

require __DIR__ . '/../../vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

try {
    $mail = new PHPMailer(true);

    $mail->CharSet = 'UTF-8';
    // $mail->Encoding = 'base64'; // 可选,PHPMailer会自动适配编码

    $mail->isSMTP();
    $mail->SMTPAuth = true;

    $mail->Host = Config::SMTP_HOST;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = Config::SMTP_PORT;

    $mail->Username = Config::SMTP_USERNAME;
    $mail->Password = Config::SMTP_PASSWORD;

    // 保留不影响的Viewport头
    $mail->addCustomHeader('Viewport', 'width=device-width, initial-scale=1.0');

    $mail->setFrom($customerEmail, $customerName);
    $mail->addAddress($sellerEmail, $sellerName);

    // 校验文件上传并添加附件
    if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        $errorMsg = match ($_FILES['file']['error']) {
            UPLOAD_ERR_INI_SIZE => '文件超过php.ini限制大小',
            UPLOAD_ERR_FORM_SIZE => '文件超过表单限制大小',
            UPLOAD_ERR_PARTIAL => '文件仅部分上传',
            UPLOAD_ERR_NO_FILE => '未选择文件',
            default => '未知上传错误',
        };
        throw new Exception($errorMsg);
    }

    $tmpFile = $_FILES['file']['tmp_name'];
    $fileName = $_FILES['file']['name'];

    if (!file_exists($tmpFile)) {
        throw new Exception('临时上传文件丢失');
    }

    $mail->addAttachment($tmpFile, $fileName);

    $mail->isHTML(true);
    $mail->Subject = $subjectForSeller;
    $mail->Body = $messageForSeller;

    $mail->send();
    echo '邮件发送成功';
} catch (Exception $e) {
    echo "发送失败:{$mail->ErrorInfo}";
}

额外提醒

  • 去Gmail的「垃圾邮件」文件夹找找,邮件可能被归类到那里。
  • 如果使用Gmail的SMTP服务,开启2FA后必须使用「应用专用密码」,不能用账号原密码。
  • 附件大小不要超过25MB,Gmail普通账号的附件上限为该数值。

内容的提问来源于stack exchange,提问作者Ovidiu-Alexandru Iftemie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:11:00