【问题标题】:How can I send an base64 image on a mail body with PHP?如何使用 PHP 在邮件正文上发送 base64 图像?
【发布时间】:2013-09-27 02:15:23
【问题描述】:

我正在尝试使用下面的代码使用 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/

【问题讨论】:

    标签: php image email base64


    【解决方案1】:

    我尝试了不同的方法,我发现的唯一方法是上传图片并获取 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,所以我不使用&lt;img src="'.$_POST['imageFromOtherPage'].'"/&gt;,而是使用生成的 URL。工作完美!

    【讨论】:

      【解决方案2】:

      我有同样的问题,最后我解决了。它可能对您有帮助: 您可以使用 SwiftMailer,但必须添加新的 Image TextHeader 'Content-Location'。 代码如下:

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

      【讨论】:

        【解决方案3】:

        获取所有图片网址的功能:

        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;
        }
        

        【讨论】:

        • 我正在使用它的修改版本,我浏览了模板的主体,并使用了 swiftmailer.org/docs/messages.html 的 $message->embed 并将 src="X" 的内容替换为此函数创建的文件的 cid .. 就像一个魅力!谢谢!
        【解决方案4】:

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

        【讨论】:

        • 我测试过,我在

          标签上写了内容并显示了正确的 base64 内容......它只是不会“翻译”为图像......

        • 您确定它显示了所有数据吗? img的大小如何?如果它是 1mb 或更多,则该帖子可以将 base64 的一部分切掉
        【解决方案5】:
        <img src="'.$_POST['imageFromOtherPage'].'"/>
        

        您的 POST 需要以 data:image/png;base64, to form a base64 encoded data: URI 开头。

        但是,即使您解决了这个问题,您正在查看邮件的电子邮件客户端也很可能根本不支持该方法。 data:URIs 是一个相对较新的现象——至少在电子邮件客户端的年表中,其中大多数仍处于发现有一种称为 CSS 的技术的过程中。电子邮件中图像的久经考验的方法是将图像嵌入为内联附件。

        以下是一些不依赖库的方法:Make PHP send an email with an inline image attachment

        但是,使用 Swiftmailer 之类的库可能会减轻很多痛苦。 Here is the appropriate Swiftmailer documentation.

        【讨论】:

          猜你喜欢
          • 2015-09-18
          • 2015-06-09
          • 2023-03-30
          • 1970-01-01
          • 2013-11-18
          • 2016-12-22
          • 1970-01-01
          • 2013-01-05
          • 2023-03-24
          相关资源
          最近更新 更多