Phpmailer auto includes local images

I'm currently busy with phpmailer and am wondering how to automatically insert local images into my email address using a script. My idea was to upload an html file and an image folder and let the script replace <imgsrc tags with cid tags.

Now, what I got so far:

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

Now I have this incomplete function that scans the html body and replaces the src tags:

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

I'm not sure what I should do here, do you extract src and replace it with cid: $ id? Since they are local images, I have no problem with src web links or any other ...

+4
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);
    }
}
+3

HTML base64?

base64, :

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

, , , .

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

All Articles