2011-06-10 131 views
1

我正在通过邮件()发送带有图像附件的电子邮件的示例。该电子邮件发送正常,图像附加,但当我试图打开图像时,浏览器告诉我它已损坏。我保存了图像,并在文本编辑器中打开它,内容仍然在base64中,如下面的代码片段所示: http://pastebin.com/B2VgarH8当使用php邮件发送带有图像附件的电子邮件时发生图像损坏()

Content-Transfer-Encoding:base64 line我假设告诉浏览器解释图像,但它什么都不做。我试着在Firefox和Chrome中打开它,结果也是一样。任何人都有一个想法,为什么它失败了?

$to = '[email protected]'; 
$subject = $matches[3][$i]; 
$bound_text = "AbC123"; 
$bound = "--".$bound_text."\r\n"; 
$bound_last = "--".$bound_text."--\r\n"; 
$headers = "From: [email protected]\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

您能否提供您的脚本产生的原始电子邮件或$ message? – Arvin 2011-06-10 14:00:14

+0

$消息格式正确,我想通过下面发布的问题,谢谢。 – radios4rabbits 2011-06-10 22:47:30

回答

1

我发现了这个问题。我调用base64_encode()两次,一次创建$ attachment,再次在$ message中进行双重编码。当客户端读取电子邮件时,它只会被解码一次,因此看起来已经损坏。现在它工作得很好。

0

看一看PHPMailer这是一个真棒类,可以轻松附加图像。

+1

但它几乎可以正常工作... – radios4rabbits 2011-06-10 11:29:00

+0

需要2分钟来实现PHPMailer的功能。 – dotty 2011-06-10 11:30:54

+0

如果你对邮件的工作方式感兴趣,可以使用mail()函数,否则就像PHPMailer一样发送邮件...... – TheHippo 2011-06-10 12:26:38

相关问题