如何使用 PHP 在邮件正文上发送 base64 图像


How can I send an base64 image on a mail body with PHP?

我正在尝试使用以下代码使用 PHP 在正文上发送一封带有 base64 图像的电子邮件,但图像从未出现......如果我更改为 URL,它可以工作,但它不适用于 base64...我只用<img src=base64>在新页面上测试了 base64 并且也工作了......我错过了什么??

<?php
    // recipients
    $to  = $_POST['email'];
    // subject
    $subject = 'Test';
    // message
    $message = '
        <html>
        <head>
         <title>Test</title>
        </head>
        <body>
            <img src="'.$_POST['imageFromOtherPage'].'"/>
        </body>
        </html>
        ';
    // To send HTML mail, the Content-type header must be set
    $headers  = 'MIME-Version: 1.0' . "'r'n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "'r'n";
    // Mail it
    mail($to, $subject, $message, $headers);
 ?>

这是我的base64图像示例:http://jsfiddle.net/28nP4/

我尝试了不同的事情,我发现的唯一方法是上传图像并获取 URL,我从这个链接中得到了它:http://j-query.blogspot.in/2011/02/save-base64-encoded-canvas-image-to-png.html

这很简单:

<?php
    // requires php5
    define('UPLOAD_DIR', 'images/');
    $img = $_POST['img'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png';
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.';
?>

这会生成一个 URL,因此,我使用生成的 URL 而不是使用 <img src="'.$_POST['imageFromOtherPage'].'"/> 。工作完美!

我有同样的问题,最后我解决了它。它可能会对您有所帮助:您可以使用 SwiftMailer,但您必须添加新的图像文本标题"内容位置"。这是代码:

$message = 'Swift_Message::newInstance()->setSubject($subject)->setFrom($fromEmail, 'Name')->setTo($toEmail)->setBcc($bccEmails);
/*get uniqueID from cid:uniqueID */
$imageID = explode(':', $message->embed('Swift_Image::fromPath('pathToTheImage')->setContentType('image/png')))[1];
/*Add Content-Location to image header*/
/** @var 'Swift_Image $image */
$image = $message->getChildren()[0];
$image->getHeaders()->addTextHeader('Content-Location', $imageID);
$message->setBody('here you will have some html with <img src=$imageID alt="Embed Image">', 'text/html');
$mailer->send($message);

获取所有图像网址的函数:

function getImagesFromMsg($msg, $tmpFolderPath)
{
    $arrSrc = array();
    if (!empty($msg))
    {
        preg_match_all('/<img[^>]+>/i', stripcslashes($msg), $imgTags);
        //All img tags
        for ($i=0; $i < count($imgTags[0]); $i++)
        {
            preg_match('/src="([^"]+)/i', $imgTags[0][$i], $withSrc);
            //Remove src
            $withoutSrc = str_ireplace('src="', '', $withSrc[0]);
            //data:image/png;base64,
            if (strpos($withoutSrc, ";base64,"))
            {
                //data:image/png;base64,.....
                list($type, $data) = explode(";base64,", $withoutSrc);
                //data:image/png
                list($part, $ext) = explode("/", $type);
                //Paste in temp file
                $withoutSrc = $tmpFolderPath."/".uniqid("temp_").".".$ext;
                @file_put_contents($withoutSrc, base64_decode($data));
            }
            //Set to array
            $arrSrc[] = $withoutSrc;
        }
    }
    return $arrSrc;
}

尝试测试 $_POST['imageFromOtherPage'] 是否包含 base64 ,可能代码对于 Post 来说太长了,你需要使用 php://input 。

<img src="'.$_POST['imageFromOtherPage'].'"/>

您的 POST 需要以 data:image/png;base64, 开头,以形成 base64 编码的 data: URI。

但是,即使您修复了此问题,您正在查看邮件的电子邮件客户端也可能根本不支持该方法。 data: URI是一个相对较新的现象 - 至少在电子邮件客户端的年表上,其中大多数仍在发现一种称为CSS的技术的过程中。电子邮件中图像的尝试和测试方法是将图像嵌入为内联附件。

以下是一些不依赖于库的方法: 让 PHP 发送带有内联图像附件的电子邮件

但是,使用像 Swiftmailer 这样的库可能会带走很多痛苦。这是相应的 Swiftmailer 文档。