使用php邮件将64位字符串作为图像嵌入到电子邮件中

时间:2012-06-25 09:09:10

标签: image base64 php

如何使用php邮件将Base64图像数据嵌入电子邮件?

<?php
$aImg = $_POST['aImage'];

$to = "abc@hotmail.com";
$subject = "Sending png image to email";

$message = "<html><head></head><body>";
$message .= '<img src="'.$aImg.'" alt="This is an Image" /></body></html>';

$headers = "Content-type: text/html";

if (mail($to, $subject, $message, $headers)) {
    echo("<p>Message successfully sent!</p>");
} else {
    echo("<p>Message delivery failed...</p>");
}
?>

运行代码后,显示“消息已成功发送”,但图像未显示出来。它显示了一个小的红十字图像。我已经调试了几个小时但仍然无法获取我的图像。目前,我正在将电子邮件发送到localhost进行测试。

2 个答案:

答案 0 :(得分:1)

这有点草率。我很久以前从网上找到的代码写了它/把它捣碎在一起,并且可能已经打破它坐在这里拔出私人信息而不戴眼镜。 :-)那时我学会了这样做的事情:chunk_split,concatenation(。),使用随机分隔符。

<?
$to="x"; // For the file to be sent.
$from="xx"; // For the from line on the received email
$name="name.ext";
$type="application/x-gzip";
            $subject="subj"
            $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
         // open the file for a binary read
            $file = fopen(**xxxxxxxxxx filepath xxxxxxxxxxxx**,'rb');
         // read the file content into a variable
         //   $data = chunk_split(base64_encode(fread($file,filesize($file))));

         // now we encode it and split it into acceptable length lines
            //ALREADY DONE, MOVE UP A FEW LINES
         // message body
            $message = "Here's that File I promised you";
         // build headers
            $headers = "From: ".$from." \r\n" .
            "MIME-Version: 1.0\r\n" .
            "Content-Type: multipart/mixed;\r\n" .
            " boundary=\"{$mime_boundary}\"";
         // put message body in mime boundries
            $message = "This is a multi-part message in MIME format.\n\n" .
            "--{$mime_boundary}\n" .
            "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
            "Content-Transfer-Encoding: 7bit\n\n" .
            $message . "\n\n";
         // attachment with mime babble
             $message .= "--{$mime_boundary}\n" .
            "Content-Type: {$type};\n" .
            " name=\"{$name}\"\n" .
            //"Content-Disposition: attachment;\n" .
            //" filename=\"{$backfile}\"\n" .
            "Content-Transfer-Encoding: base64\n\n" .
            chunk_split(base64_encode(fread($file,filesize(**xxxxxxxxxx filepath xxxxxxxxxxxx**)))) . "\n\n" .
            "--{$mime_boundary}--\n";
// close the file
fclose($file);
         // send mail
            mail($to, $subject, $message, $headers)
             ?>

答案 1 :(得分:0)

如果您曾尝试过“查看源代码”,那么它将为您提供关于此处发生的事情的第一条线索。

这不是微不足道的,有多种方法可以解决问题。但是你前进的路程很长。

假设您想要将图像直接包含在电子邮件中而不是HTTP URL或附件中,那么您需要将其包含在data url中 - 这只适用于最近的浏览器/邮件代理。

或者你只需​​将它作为附件添加到任何电子邮件中 ​​- 但创建mime消息并非易事 - 使用其中一个现成的软件包,如swiftmailer或phpmailer。

第三种方法是创建一个封装的MIME http web archive file,但我不知道在PHP中创建这些文件的任何现成的包。此外,我认为这些文件仅受MSOutlook,MSIE和Opera支持(即使这样,MS实现也存在很多问题)。