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

PHP Mail()发送邮件内嵌图片仅Gmail显示异常求助

Gmail内嵌图片显示异常的解决方案

Gmail会自动代理所有外部图片链接,在URL后附加追踪参数,若你的图片服务器对请求URL有严格匹配校验,或返回的响应头不符合Gmail要求,就会导致代理后的链接无法加载图片,且Gmail不会显示「显示图片」选项。以下是可行的解决方法:

方案1:使用CID将图片作为附件嵌入(推荐)

这是邮件内嵌图片的标准RFC兼容方式,所有客户端都支持,彻底规避外部链接的问题。

修改后的PHP脚本示例:

$to = 'email@example.com';
$subject = 'Welcome to the Playtest Program';

// 读取本地图片文件
$imagePath = '/path/to/your/maxent-email_logo.png';
$imageData = file_get_contents($imagePath);
$imageBase64 = base64_encode($imageData);
$imageType = mime_content_type($imagePath); // 需启用php_fileinfo扩展

// 生成唯一Content-ID
$cid = uniqid() . '@example.com';

// 构造邮件内容,用cid引用图片
$message = "<img src=\"cid:$cid\" /><br /><br />";
// ... 其余邮件内容

// 设置MIME边界
$boundary = uniqid();

$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/related; boundary=\"$boundary\"\r\n";
$headers .= "From: noreply@example.com\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();

// 组装邮件主体
$body = "--$boundary\r\n";
$body .= "Content-Type: text/html; charset=UTF-8\r\n";
$body .= "\r\n";
$body .= $message . "\r\n";

// 添加图片附件段
$body .= "--$boundary\r\n";
$body .= "Content-Type: $imageType\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-ID: <$cid>\r\n";
$body .= "Content-Disposition: inline\r\n";
$body .= "\r\n";
$body .= $imageBase64 . "\r\n";

// 闭合边界
$body .= "--$boundary--";

// 发送邮件
if(mail($to, $subject, $body, $headers)){
    echo '<h1>mail sent</h1>';
}else{
    echo '<h1>mail NOT sent</h1>';
}

方案2:Base64直接嵌入HTML

将图片编码为Base64后直接写入img标签,无需附件,适合小体积图片(避免邮件过大被拦截)。

修改邮件内容部分:

// 读取图片并编码
$imagePath = '/path/to/your/maxent-email_logo.png';
$imageData = base64_encode(file_get_contents($imagePath));
$imageType = mime_content_type($imagePath);

// 构造内嵌图片的img标签
$message = "<img src=\"data:$imageType;base64,$imageData\" /><br /><br />";
// ... 其余邮件内容

方案3:调整图片服务器响应头

若坚持使用外部链接,需确保图片服务器返回的响应头符合Gmail要求:

  • 正确返回Content-Type(如image/png)
  • 不要设置严格的Referer校验(Gmail代理请求的Referer为Gmail域名)
  • 确保HTTPS证书有效,无安全警告
  • 添加Cache-Control: public等合理缓存头,允许Gmail缓存图片

可通过curl检查响应头:

curl -I https://example.com/maxent-email_logo.png

内容的提问来源于stack exchange,提问作者stinkysGTI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 08:13:17