我尝试使用PHPMailer发送带有图片的HTML邮件。从html文件加载或复制正文,其中包含所有信息。
那么如何从body中动态地找到内联图像并将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;
}
答案 0 :(得分:0)
要检索与每个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)
闭包结合使用。这样我们就可以在$images
内找到preg_replace_callback
。
// 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;
?>