我目前正忙着使用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? 由于它们是本地图像,我没有web src链接或其他任何问题...
答案 0 :(得分:3)
你有正确的方法
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);
}
}
答案 1 :(得分:0)
为什么不将图像直接嵌入到base64的HTML中?
你只需要在base64中转换你的图像,然后像这样包含它们:
<img src="data:image/jpg;base64,---base64_data---" />
<img src="data:image/png;base64,---base64_data---" />
我不知道这是否与你的情况有关,但我希望它有所帮助。
答案 2 :(得分:0)
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);
}
}
}