doujiexin1136 2011-06-10 11:17
浏览 115
已采纳

使用php mail()发送带有/ image附件的电子邮件时损坏的图像

I'm following from an example of sending an email with image attachment through mail(). The email gets sent fine and the image is attached but when I attempt to open the image the browser tells me it's corrupt. I saved the image and opened it up in a text editor and the contents are still in base64, as seen in this snippet of the file: http://pastebin.com/B2VgarH8

The Content-Transfer-Encoding: base64 line I assumes tells the browser to interpret the image but it does nothing. I've tried opening it in Firefox and Chrome and it's the same result. Anyone have an idea why it's failing?

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

" . (string)$matches[5][$i] . "
" . $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\"
" .
    "Content-Transfer-Encoding: base64
" .
    "Content-disposition: attachment

" .
    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';
}
  • 写回答

2条回答 默认 最新

  • dtkmejg127475 2011-06-10 22:51
    关注

    I found out the problem. I'm calling base64_encode() twice, once when creating $attachment and again in the $message making it doubly encoded. When the email is read by the client it's only decoded once so it appears corrupt. It's working fantastic now.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么在stm32门禁成品上增加记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 解riccati方程组