2013-11-15 50 views
4

我目前正在忙於phpmailer,並想知道如何使用腳本自動在本地電子郵件中嵌入本地圖像。我的想法是上傳一個html文件和一個包含圖像的文件夾,並讓腳本將<img src標籤替換爲cid標籤。phpmailer自動包含本地圖像

現在我走到這一步是:

$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鏈接或任何其他問題...

回答

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); 
    } 
} 
0

爲什麼你不直接在base64中的HTML中嵌入圖像?

你只需要將圖像轉換爲Base64,然後將它們包括像這樣:

<img src="data:image/jpg;base64,---base64_data---" /> 
<img src="data:image/png;base64,---base64_data---" /> 

我不知道這是不是你的情況或不相關,但我希望它能幫助。

+0

我不知道的PHPMailer知道如何處理這些東西。當我只是發送一個郵件與身體(提供了一個MIME類型),它不顯示爲圖片..這就是爲什麼我去爲phpmailer –

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); 
     } 
    } 
}