Main Content

Reading and using emails including enclosures on your web server.

Archive - Originally posted on "The Horse's Mouth" - 2011-09-23 18:44:24 - Graham Ellis

The imap module ships with PHP, but isn't always built into the server; you need to build PHP with --with-imap if it's not there. But once you do have the module , you can access your POP3 email server direct from PHP.

Very recently, I was asked if I could extract attachments / enclosures from emails sent to the web server, and save them there into a database, with the attach,ents and enclosures in a usable form. Such emails are typically multipart, and I like a challenge. But it turns out to be fairly straightforward once the imap module is loaded and you understand how it works.

1. imap_open established a connection to the IMAP server (the question asked about this being the web server, but it could be any computer that's a mial seever)

2. imap_headers finds out what's in the mailbox for you.

3. A loop of imap_fetchstuctures gets details of each email and within that

4. A loop of imap_fetchbodys looks at the main and (if present) subparts of each message.

Functions such as imap_base64 and imap_qprint may be used to convert encoded content back to the original enclose, and imap_fetchmime or the type and subtype fields may be used to identify content type, thus disposition.

Full source code of the demo is [here]. Saving to a database rather than a plain text file is "trivial" ... or at least beyond the scope of this demo, and something that's covered here in many places already. The picture illustrating this item show sample output, including an image that the PHP has extracted from email.

My original questioner was looking for a handler that wasn't in fact interactive - that took emails as they arrived and saved them away to server files. That could be done through a PHP script running via crontab rather than via a webserver, or the whole job could be silently run from time to time within a regular user's request, in the same way that PHP cleans up abandoned sessions. There is a VERY old example of this [here] - from before we took the lazy practical approach of using PHP's new (at the time) $_SESSION array.


Footnotes -

1. I should warn you to think carefully about the security issues involved in fishing stuff out of emails and making automatic use of it on your server

2. The imap module also allows you to delete and send emails, mark them as read, etc - so you can write yourself a full webmail client if you want.