【发布时间】:2011-08-11 18:30:41
【问题描述】:
我一直在尝试将图像编码为 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 文本。
【问题讨论】:
-
不要建立自己的 mime 电子邮件。使用Swiftmailer 或PHPMailer 并为自己省去所有这些麻烦。他们都可以轻松地做附件和内嵌图片,
-
@Marc - 这是个好主意,但我没有这个项目的奢侈。