PHP:mail()附加base64图像以文本形式出现

时间:2011-08-11 18:30:42

标签: png base64 php

我一直在尝试将图像编码为base64,然后使用php mail()将其作为电子邮件附件发送,但我得到的只是我的电子邮件中的base64文本。这是我正在使用的:

$boundary1 = 'bound1';
$boundary2 = 'bound2';
$to = 'test@me.com';  
$subject = 'Test Image attachment'; 
$headers = 'From: "Me" <me@myemail.com>'."\r\n"; 
//add boundary string and mime type specification 
$headers .= "MIME-Version: 1.0\r\n"; 
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary1\""; 
//define the body of the message. 
$message = 'Content-Type: image/png; name="'.$file_name.'"'."\n"; 
$message .= "Content-Transfer-Encoding: base64\n"; 
$message .= "Content-Disposition: inline; filename=\"$file_name\"\n\n";
$message .= base64_encode_image("signature_files/".$file_name, 'png')."\n";
$message .= "--" . $boundary2 . "\n";
//send the email 
mail( $to, $subject, $message, $headers);

// Function to encode an image
function base64_encode_image($filename=string,$filetype=string) {
    if ($filename) {
        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
        return 'data:image/' . $filetype . ';base64,' . chunk_split(base64_encode($imgbinary), 64, "\n");
    }
}

有没有人发现这段代码有什么问题?我收到电子邮件时,真的不确定为什么我只看到RAW文本。

2 个答案:

答案 0 :(得分:0)

您分别在邮件标题和MIME附件部分标题中混合了\r\n\n\n。请尝试将它们全部更改为\r\n

另一种可能性 - 如果您尝试附加图片,而不是显示内嵌,请使用Content-disposition: attachment;

$message .= "Content-Disposition: attachment; filename=\"$file_name\"\n\n";

答案 1 :(得分:0)

这是使用内联base64图像发送HTML电子邮件的正确方法:

<?php
$boundary = md5(uniqid(time()));

$header[] = "MIME-Version: 1.0";
$header[] = "Content-Type: Multipart/Mixed; Boundary=\"$boundary\"";
$header[] = "Content-Transfer-Encoding: 7bit";
$header[] = "From: John Doe <john.doe@pbx.com>";
$header[] = "Reply-To: John Doe <john.doe@pbx.com>";
$header[] = "X-Mailer: PHP/".phpversion();

$msg[] = "";
$msg[] = "--{$boundary}";
$msg[] = "Content-Type: text/html; charset=ISO-8859-1";
$msg[] = "";
$msg[] = "<p>YOUR HTML CONTENT</p> <img src=\"cid:logo\" alt=\"Logo\">";
$msg[] = "";
//HERE YOU MUST ATTACH THE IMAGE
//===============================================
$image = chunk_split(YOUR_IMAGE_ENCODED_IN_BASE64);
$msg[] = "--{$boundary}";
$msg[] = "Content-Type: image/png; name=\"logo.png\"";
$msg[] = "Content-ID: <logo>";
$msg[] = "Content-Description: Attachment";
$msg[] = "Content-Transfer-Encoding: base64";
$msg[] = "Content-Disposition: inline; filename=\"logo.png\"";
$msg[] = "";
$msg[] = $image;
$msg[] = "";

$msg[] = "--{$boundary}--";
mail($mailto, $subject, implode("\r\n", $msg), implode("\r\n", $header));

这里的重要部分是内容ID参考,因此,首先,您必须定义图像ID,在这种情况下,ID是徽标,因此,在附件中,您必须定义内容ID标头:

Content-ID: <logo>

然后,您可以在HTML内容中通过内容ID调用或内联此图像,如下所示:

<img src="cid:logo" alt="Logo">