我正在使用 phpMailer 发送使用 tinymce 编辑器编写并保存在 MySQL 中的电子邮件。
我遇到的问题是当图像通过 tinymce 上传时,它返回一个外部 URL 并且图像显示在编辑器中,然后当电子邮件发送时,它通过外部 URL 附加图像,我想更改它以附加图像并改用 CID。
我尝试使用
$email->msgHTML($body);
但这没有用。
我也试过这个:
$doc = new DOMDocument();
@$doc->loadHTML($body);
$tags = $doc->getElementsByTagName('img');
$i = 0;
foreach($tags as $tag) {
$i++;
$tag->setAttribute('src', 'image'.$i);
$email->AddEmbeddedImage($tag->getAttribute('src'), 'cid:image'.$i);
}
$body = $doc->saveHTML();
但这会阻止图像在电子邮件中显示。
有没有一种方法可以将外部图像制作成 CID,这样电子邮件就不会依赖外部链接了。
这个问题,有朋友帮忙,基本上他说什么我就贴什么;希望对您有所帮助!
addStringEmbeddedImage
功能可以通过更改电子邮件正文的文本将图像 URL 替换为 CID 引用来将图像附加到电子邮件。
$doc = new DOMDocument();
@$doc->loadHTML($body);
$tags = $doc->getElementsByTagName('img');
// Loop through each <img> tag and replace the external URL with a CID reference
foreach ($tags as $tag) {
$url = $tag->getAttribute('src');
$cid = md5($url); // Generate a unique CID for each image
$tag->setAttribute('src', 'cid:' . $cid); // Replace the URL with the CID reference
$image_data = file_get_contents($url); // Get the image data from the URL
$email->addStringEmbeddedImage($image_data, $cid); // Attach the image to the email using the CID reference
}
$body = $doc->saveHTML();
$email->Body = $body;
$email->IsHTML(true);
$email->send();
此代码示例将电子邮件正文中每个
src
标签的 <img>
属性替换为从图像 URL 的 MD5 哈希派生的 CID 引用。
addStringEmbeddedImage
函数 - 需要图像数据作为第一个参数,CID 引用作为第二个参数 - 用于在使用 file_get_contents()
从 URL 检索图像数据后将其附加到电子邮件。