【问题标题】:How to display multiple inline images in email body when we are sending mail with dynamic content using phpMailer当我们使用 phpMailer 发送带有动态内容的邮件时,如何在电子邮件正文中显示多个内联图像
【发布时间】:2017-01-17 13:15:06
【问题描述】:

我正在尝试使用 PHPMailer 发送带有图像的 HTML 邮件。正文是从包含所有信息的 html 文件加载或复制的。

那么我怎样才能动态地从正文中找到内联图像并将 AddEmbeddedImage() 方法应用于它。

PHP 代码

  $mail->addReplyTo($from, $fromName);
    $mail->addBCC($from);
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->AddEmbeddedImage($filepath, $filecid, $filename);
   if(!$mail->send()) 
            {
                echo "Failed To Send Mail";
                exit;
            } 
            else
            {
                echo "Mail Has Been Sent";
                exit;

            }

【问题讨论】:

  • 在 HTML 文件的正文中,您是否使用 PHP Mailer CID <img src="cid:my-attach"> 或 <img src="./actual/path/to/file1.jpg"> 进行标记?
  • 是的,我有 PHP Mailer CIDs ...
  • 如果 cid 'my-attach' 总是匹配 'my-attach.jpg' 或 'my-attach.png' 并且文件都位于同一个文件夹中,您可以轻松地遍历所有图像, 这是你想要的吗?还是图像并不总是以 cid 和文件位置命名?
  • 是的,通过这种方式接收者可以查看收件箱的邮件内容的图像,但是我如何在发件人侧的已发送邮箱的邮件内容中显示图像。
  • 哦,自己预览一下(就像发送前一样)

标签: php phpmailer


【解决方案1】:

要检索与每个 cid 关联的文件路径,我们需要一个与图像源相关的 cid 列表。

<?php

    // Create associative array for images
    // Relation syntax: cid => filename
    $images = array(
        'file-1' => './src/file-1.png',
        'file-2' => './src/file-2.png',
        'file-3' => './src/file-3.png'
    );

    // Retrieve the body contents
    $body = file_get_contents('src/body.html');

接下来,使用preg_replace_callback 获取所有图像,以便能够以不同的方式处理每个图像源。 将匿名函数 function($matches) 与 use ($images) 闭包结合使用。这样我们就可以在preg_replace_callback 中使用$images。

    // Create body
    $body = preg_replace_callback(

        // Regex for finding image sources
        '/<img(.*?)src=[\'|\"](.*?)[\'|\"](|.*?)>/',

        // Callback
        function($matches) use ($images){

            // For rebuilding the <img> tag
            $beforeImageSRC = $matches[1];
            $afterImageSRC  = $matches[3];

            // Image source
            $imageSRC       = $matches[2];

然后,验证找到的源是否实际上是 PHPMailer cid。还要检查我们的$images数组中是否存在找到的cid。

            // Is this source a PHPMailer cid?
            if(preg_match('/^cid:/', $imageSRC)){

                $fileCID    = preg_replace('/^cid:/', '', $imageSRC);

                // Does the cid exist in our associative array?
                if(isset($images[$fileCID])){

                    // Update image source if we have it listed in array
                    $imageSRC = $images[$fileCID];

                }

            }

最后,重建图像标签并将其返回到正文并打印正文以在浏览器中预览输出。

            return '<img' . $beforeImageSRC . 'src="' . $imageSRC . '"' . $afterImageSRC . '>';
        },
        $body);

    print $body;

?>

【讨论】:

    猜你喜欢
    • 2019-01-20
    • 2017-02-23
    • 1970-01-01
    • 2015-03-10
    • 2014-06-02
    • 2015-11-20
    • 2015-08-29
    • 2014-12-24
    • 1970-01-01
    相关资源
    最近更新 更多