Skip to content

Instantly share code, notes, and snippets.

@InToSSH
Last active November 17, 2020 11:08
Show Gist options
  • Save InToSSH/d7f43ee76b6c0873f7a4ee56116086fc to your computer and use it in GitHub Desktop.
Save InToSSH/d7f43ee76b6c0873f7a4ee56116086fc to your computer and use it in GitHub Desktop.
This function looks up images in the HTML email body content that are encoded in Base64, attaches them to the Swift_Message, replaces the Base64 with CID and returns modified body.
protected function replaceBase64ImagesWithCid($content, Swift_Message $message)
{
return preg_replace_callback(
"/(<img[^>]*src *= *[\"']?)([^\"']*)/i",
function ($matches) use ($message) {
$is_base64 = preg_match("/data:([a-z]+\/[a-z]+);base64,(.*)/i", $matches[2], $image_data);
if ($is_base64) {
$contentType = $image_data[1];
list($type, $ext) = explode("/", $contentType);
$base64 = $image_data[2];
$filename = uniqid("image_") . "." . $ext;
$cid = $message->embed(new Swift_Image(base64_decode($base64), $filename, $contentType));
return $matches[1] . $cid;
}
return $matches[0];
},
$content
);
}
@InToSSH
Copy link
Author

InToSSH commented Nov 16, 2020

Swift Mailer - Convert Base64 images to CID

This function looks up images in the HTML email body content that are encoded in Base64, attaches them to the Swift_Message, replaces the Base64 with CID and returns modified body.

You just have to provide original content and an instance of Swift_Message to attach the images to.

Sample usage

$message = (new Swift_Message($subject))
            ->setFrom([$from_email => $from_name])
            ->setTo([$to_email]);

$message->setBody($this->replaceBase64ImagesWithCid($content, $message), 'text/html');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment