tutorial: addEmbeddedImage phpmailer
What is addEmbeddedImage() :-
If you want to make a HTML e-mail that refers to images that are also attached to the message (as opposed to pointed at remotely), it's necessary to attach the image with a content identifier and then link the tag to it. For example, if you add an image as inline attachment with the content ID of my-photo, you would access it within the HTML body using
< img src="cid:my-photo" alt="my-photo">.
In detail, here is the function to add an embedded attachment:
$mail->addEmbeddedImage($filename, $cid);
The process of connecting image tags to content identifiers is a bit complicated, but the msgHTML() method can do most of the work for you.
⦁ For Single Image in HTML:-
It is very easy for sending single image in html.
$this->AddEmbeddedImage('/path/to/image.jpg', 'my-image', 'attachment', 'base64', 'image/jpeg');
// replace source with id
< img src="cid:my-image" alt="" />
⦁ For Multiple Images in HTML :-
For more images that are contained in your HTML template, you need an automatic way to do this. Here is the custom function I have written for this.
function embed_images(&$body)
{
// get all img tags
preg_match_all('/<img.?>/', $body, $matches);
if (!isset($matches[0])) return;
// foreach tag, create the cid and embed image
$i = 1;
foreach ($matches[0] as $img)
{
// make cid
$id = 'img'.($i++);
// replace image web path with local path
preg_match('/src="(.?)"/', $body, $m);
if (!isset($m[1])) continue;
$arr = parse_url($m[1]);
if (!isset($arr['host']) || !isset($arr['path']))continue;
// add
$this->AddEmbeddedImage('/home/username/'.$arr['host'].'/public'.$arr['path'], $id, 'attachment', 'base64', 'image/jpeg');
$body = str_replace($img, '', $body);
}
}
⦁ Example:-
⦁ Using embedded image in html Email.
⦁ Without embedded image in html Email.
Posted on Utopian.io - Rewarding Open Source Contributors
As always very nice content
thanks alot, do you use php?
I am gonna learn it in school
nice! I follow informatics :)
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
thank you
useful thanks brother
thanks!
Hey @brothermic I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x