PHPMailer addStringEmbeddedImage并多次添加相同的图像

时间:2017-10-24 20:44:50

标签: php image base64 phpmailer

因此,在PHPmailer中,如果使用addStringEmbeddedImage,则可以将64base编码图像添加到邮件正文中;在数据部分中,您可以添加64位编码图像。例如:

$mail->addStringEmbeddedImage(base64_decode($str), "img_".$i, "img_".$i,"base64",$type);  

我以base64格式从文本编辑器中获取图像,然后用相应的容器替换图像

<img src=\"cid:img_".$i."\" ".$height. " " .$width. ">"

它工作正常,但出于某种原因,一旦我添加一个图像不止一次,无论是下一个图像还是第一个和最后一个图像,邮件只会保存(?)第一张图片。不是它没有显示它,因为在原始邮件中你可以看到它中只指定了一个容器。

--boundary
Content-Type: image/png; name="img_1"
Content-Transfer-Encoding: base64
Content-ID: <img_1>
Content-Disposition: inline; filename="img_1"

正如你所看到的,每个图像都有不同的id(这是它们在电子邮件中的顺序),它唯一能告诉它的是同一图像是由解码的base64图像所以我真的不知道为什么这个只有当它的图像相同时才会发生。我可以添加img1 ---- img2 ---- img1 ---- img3它会显示img1 ---- img2 ---- | emptycontainer | ---- img3

编辑:所以作为参考,这是我用来提取所有图像的时间

 //$body of the mail, all the images i want to replace have that alt"" at the start
while(strstr($body, "<img alt")){
            $i++;
            $start= strpos($body, "<img alt");
            $end= strpos($body,">",$start);
            $str = substr($body,$start,$end-$start);


            $height = "";
            $width = "";
            if (strstr($str, "height:")){
                $ini = strpos($str, "height:")+7;
                $fin = strpos($str,";",$ini);
                $height = "height= \"".substr($str,$ini,$fin-$ini-2)."\"";
            }
            if (strstr($str, "width:")){
                $ini = strpos($str, "width:")+6;
                $fin = strpos($str,"\"",$ini);
                $width = "width= \"".substr($str,$ini,$fin-$ini-2)."\"";
            }
            //here i replace the whole image with a container
            $body= substr_replace($body, "<img src=\"cid:img_".$i."\" ".$height. " " .$width. ">", $start,$end-$start+1);

            //get the type after data:
            $start= strpos($str, "data:");
            $end= strpos($str,";",$start);
            $type= substr($str, $start+5, $end-$start-5);

            //and this is where i get the base64 string
            $start= strpos($str, "base64,");
            $end= strpos($str,"\"",$start);
            $str = substr($str, $start+7, $end-$start-7);
            $mail->addStringEmbeddedImage(base64_decode($str), "img_".$i, "img_".$i,"base64",$type);  
        } 

感谢您的帮助和感谢阅读

1 个答案:

答案 0 :(得分:0)

我可以看到为什么你会在消息中使用多个相同的图像,但为什么你会多次连接同一个图像来实现呢? cid值的重点在于它们允许您从多个位置引用相同的图像,因此如果您在页眉和页脚中都有徽标图像,则可以将其附加一次并从中引用两个地方,减少邮件大小。我怀疑你的问题是你正在尝试解决这个问题并通过附加两个cid值的相同图像数据而失败,但PHPMailer注意到数据是相同的而没有做第二个附件,让你的第二个cid指向什么。您可以通过对两个图像标记使用相同的cid值来修复它。

这应该有你提到的问题:

$img = base64_decode($str);
$mail->addStringEmbeddedImage($img, "img_1", "img_1", "base64", $type);
$mail->addStringEmbeddedImage($img, "img_2", "img_2", "base64", $type);

<img src="cid:img_1">
<img src="cid:img_2">

这应该有效:

$img = base64_decode($str);
$mail->addStringEmbeddedImage($img, "img_1", "img_1", "base64", $type);

<img src="cid:img_1">
<img src="cid:img_1">

代码计算内容的SHA256哈希,并使用它来检查它们是否相同。

相关问题