Home / PHP email message class for extracting attachments

PHP email message class for extracting attachments

I've done a bit of work in the past extracting attachments from email with PHP and posted a few articles here showing how to do it. None of them have really been all that satisfactory and so a little earlier this year I started again from scratch. I've posted here what is a work-in-progress due to requests from several people. It's not complete but it does work.

Notes about the email class

When working on it, I discovered just how difficult it is to actually get information out of emails because email clients format emails differently, and also differently depending on whether there are attachments, inline attachments, html and/or plain text body parts.

This class recursively loops through the email and finds all the attachements including email messages themselves that may have been attached and recurses through those too. While doing all this it puts the html and plain text body of the top level message into the bodyHTML and bodyPlain properties.

Unfortunately I didn't write any comments through the code because I was intending to get it finished at the time and write a blog about it which would have served that function, but time ran away from me.

Basically the format of a message is in "parts" and they can be like e.g. 1, 1.1, 1.2, 1.2.1, 1.2.2, etc and you need those numbers to be able to get the "attachments". I worked out through trial and error with many emails that the order and numbering varies considerably.

At some point in the future I will do some more work on this code, making it more usable for email in general, adding commenting etc and probably post it to GitHub.

Download the email class

Download it here.

The file is a plain text PHP file, compressed as a zip file. I can't really offer any support for this code so it's really up to you to try it out and see what you can do with it.