我是通过邮件()发送带有图片附件的电子邮件的示例。电子邮件被发送正常并且图像被附加但当我尝试打开图像时,浏览器告诉我它已损坏。我保存了图像并在文本编辑器中将其打开,内容仍在base64中,如文件的片段所示: 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';
}
答案 0 :(得分:1)
我发现了问题。我正在调用base64_encode()两次,一次创建$ attachment时再次调用$ message,使其成为双重编码。当客户端读取电子邮件时,它只会被解码一次,因此它看起来已损坏。它现在很棒。
答案 1 :(得分:0)
看看PHPMailer这是一个很棒的课程,可以轻松附加图像。