clarkk
clarkk

Reputation: 27689

extract images from email

I need to generate HTML files with additional images from emails

All data is fetched with php_imap

img tag in email

<img alt="" src="cid:[email protected]">

I got multiple img tags, but how to extract the actual image part cid:[email protected] from the email and save it as a file?

Upvotes: 2

Views: 1958

Answers (2)

clarkk
clarkk

Reputation: 27689

Extract the images from the email

http://www.electrictoolbox.com/php-email-extract-inline-image-attachments/

Upvotes: 0

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

Grabbing the image source

You can do this by using DomDocument and DOMXpath to query for the image src.

$doc = new DOMDocument();
$doc->loadHTML($email); //load the string into DOMDocument   
$selector = new DOMXPath($doc); //create a new domxpath instance
$images = $selector->query('//img/@src'); //Query the image tag and get the src
foreach ($images as $item) {
   echo $item->value; //grab the value (output: cid:[email protected])
}

https://eval.in/477064

Saving as a file

Now that you've grabbed the image source, you can just write the contents to a file. This does mean you'll need allow_url_fopen on.

foreach ($images as $item) {
   $content = file_get_contents($item->value);
   file_put_contents('./'.str_replace("/", "-", ltrim(parse_url($item->value)['path'],'/')), $content );
}

Having the foreach supports multiple images within the e-mail body

Upvotes: 1

Related Questions