开发者

Corrupt image when sending an email w/ image attachment using php mail()

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."\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开发者_JAVA技巧" .
    "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';
}


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.


Have a look at PHPMailer it's an awesome class which can attach images with ease.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜