>我目前正忙于phpmailer,想知道如何使用脚本自动将本地图像嵌入到我的电子邮件中。我的想法是上传一个 html 文件和一个包含图像的文件夹,并让脚本将<img
src 标签替换为 cid 标签。
现在我到目前为止得到的是:
$mail = new PHPMailer(true);
$mail->IsSendmail();
$mail->IsHTML(true);
try
{
$mail->SetFrom($from);
$mail->AddAddress($to);
$mail->Subject = $subject;
$mail->Body = embed_images($message, $mail);
$mail->Send();
}
现在我有这个不完整的函数,可以扫描 html 正文并替换 src 标签:
function embed_images(&$body, $mailer)
{
// get all img tags
preg_match_all('/<img.*?>/', $body, $matches);
if (!isset($matches[0])) return;
$i = 1;
foreach ($matches[0] as $img)
{
// make cid
$id = 'img'.($i++);
// now ?????
}
$mailer->AddEmbeddedImage('i guess something with the src here');
$body = str_replace($img, '<img alt="" src="cid:'.$id.'" style="border: none;" />', $body);
}
我不确定我应该在这里做什么,您是否检索 src 并将其替换为 cid:$id ?由于它们是本地图像,我没有网络 src 链接或其他什么的麻烦......
你有正确的方法
function embed_images(&$body,$mailer){
// get all img tags
preg_match_all('/<img[^>]*src="([^"]*)"/i', $body, $matches);
if (!isset($matches[0])) return;
foreach ($matches[0] as $index=>$img)
{
// make cid
$id = 'img'.$index;
$src = $matches[1][$index];
// now ?????
$mailer->AddEmbeddedImage($src,$id);
//this replace might be improved
//as it could potentially replace stuff you dont want to replace
$body = str_replace($src,'cid:'.$id, $body);
}
}
为什么不直接在base64的HTML中嵌入图像?
您只需要在base64中转换图像,然后像这样包含它们:
<img src="data:image/jpg;base64,---base64_data---" />
<img src="data:image/png;base64,---base64_data---" />
我不知道这是否与您的情况相关,但我希望它有所帮助。
function embed_images(&$body, $mailer) {
// get all img tags
preg_match_all('/<img[^>]*src="([^"]*)"/i', $body, $matches);
if (!isset($matches[0]))
return;
foreach ($matches[0] as $index => $img) {
$src = $matches[1][$index];
if (preg_match("/'.jpg/", $src)) {
$dataType = "image/jpg";
} elseif (preg_match("/'.png/", $src)) {
$dataType = "image/jpg";
} elseif (preg_match("/'.gif/", $src)) {
$dataType = "image/gif";
} else {
// use the oldfashion way
$id = 'img' . $index;
$mailer->AddEmbeddedImage($src, $id);
$body = str_replace($src, 'cid:' . $id, $body);
}
if($dataType) {
$urlContent = file_get_contents($src);
$body = str_replace($src, 'data:'. $dataType .';base64,' . base64_encode($urlContent), $body);
}
}
}