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


Embed base 64 string as image into email using php mail

如何使用php mail将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>");
}
?>

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

这有点草率。我很久以前就从网上找到的代码中编写/将其捣碎在一起,并且可能已经打破了它,坐在这里不戴眼镜就拿出私人信息。:-)我当时学到的东西是:chunk_split,串联(.),使用随机分隔符。

<?
$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)
             ?>

如果您尝试过"查看源代码",它会为您提供有关这里发生的事情的第一个线索。

这并非微不足道,有多种方法可以解决问题。但你还有很长的路要走。

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

或者,您可以简单地将其作为附件添加到任何电子邮件中 - 但创建 mime 消息并非易事 - 使用现成的软件包之一,例如 swiftmailer 或 phpmailer。

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