【问题标题】:Corrupt image when sending an email w/ image attachment using php mail()使用 php mail() 发送带有/图像附件的电子邮件时损坏图像
【发布时间】:2011-09-12 10:20:56
【问题描述】:

我正在关注一个通过 mail() 发送带有图像附件的电子邮件的示例。电子邮件发送正常并附上了图像,但是当我尝试打开图像时,浏览器告诉我它已损坏。我保存了图像并在文本编辑器中打开它,内容仍然是 base64,如文件的这个 sn-p 所示: http://pastebin.com/B2VgarH8

我假设的 Content-Transfer-Encoding: base64 行告诉浏览器解释图像,但它什么也没做。我试过在 Firefox 和 Chrome 中打开它,结果是一样的。有人知道为什么会失败吗?

$to = 'admin@hostoi.com';
$subject = $matches[3][$i];
$bound_text = "AbC123";
$bound = "--".$bound_text."\r\n";
$bound_last = "--".$bound_text."--\r\n";
$headers = "From: me@gmail.com\r\n";
$headers .= "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$bound_text\"";
$message = "If you can see this MIME than your client doesn't accept MIME types!\r\n" . $bound;
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n" .
    "Content-Transfer-Encoding: 7bit\r\n\r\n" . (string)$matches[5][$i] . "\r\n" . $bound;

$attachment = chunk_split(base64_encode(file_get_contents($matches[1][$i])));
$attachment_ext = substr(strrchr($matches[1][$i], '.'), 1);
$attachment_ext = $attachment_ext == 'jpg' ? 'jpeg' : $attachment_ext;
$attachment_name = time() . "_" . rand(10,99) . "." . $attachment_ext;

$message .= "Content-Type: image/$attachment_ext; name=\"$attachment_name\"\r\n" .
    "Content-Transfer-Encoding: base64\r\n" .
    "Content-disposition: attachment\r\n\r\n" .
    chunk_split(base64_encode($attachment)) . $bound_last;

if(mail($to, $subject, $message, $headers)) {
    echo 'MAIL SENT';
    //mysql_query("INSERT INTO message(body) VALUES(" . mysql_real_escape_string($matches[5][$i]) . ")", $dbh);
} else {
    echo 'MAIL FAILED';
}

【问题讨论】:

  • 您能否提供您的脚本生成的原始电子邮件消息或$message
  • $message 格式正确,我发现了问题,我将在下面发布,谢谢。

标签: php image email attachment corrupt


【解决方案1】:

看看PHPMailer,这是一个很棒的课程,可以轻松附加图片。

【讨论】:

  • 用 PHPMailer 实现你所拥有的需要 2 分钟。
  • 如果您对邮件的工作原理感兴趣,请使用 mail() 函数,否则请使用 PHPMailer 之类的东西,然后发送邮件...
  • 我同意兔子为什么要实现一个单独的类,如果没有它也能很好地工作
【解决方案2】:

我发现了问题。我调用 base64_encode() 两次,一次是在创建 $attachment 时,另一次是在 $message 中,使其双重编码。当客户端读取电子邮件时,它仅被解码一次,因此它看起来已损坏。现在效果很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-22
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 2018-03-09
    • 1970-01-01
    • 2011-11-09
    相关资源
    最近更新 更多