Last active
November 17, 2020 11:08
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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