Simple Local Mailbox Parser
Out of frustration from trying to use PHP’s IMAP library for local mail, I decided to bite the bullet and write my own simple MBOX parser. In the event it might help anyone, I’m posting it here. It parses a mailbox for messages (including multipart messages) and returns them in a simple associative array.
Readme:
Call this function to parse a mailbox:
$messages = parse_mbox(path, [expunge])
| path: | The absolute path to the mailbox file. It’s probably /var/mail/USERNAME or /var/spool/mail/USERNAME. |
| expunge: | If set to true, the mailbox file will be emptied. All messages that were in the mailbox file will be appended a backup file with the same name as the original mailbox, but with the current date included in the filename, i.e. /var/mail/USERNAME.04-15-2006 |
Return value: An associative array with the following structure:
(
‘headers’ => Array
(
Other headers…
),
‘content’ => ‘Message Content (not set for multipart messages)’,
‘parts’ => Array
(
(
‘content’ => …
‘parts’ => …
)
Other parts
)
)
If a message is multipart, its parts are places in the ‘parts’ arrray (i.e. message["parts"]). Each part is essentially its own message; it has its own headers and either content or parts - each message part can be multipart and have its own parts, which can in turn be multipart and so forth.
If a message part is base64 encoded, it should be sufficient to use PHP’s base64_decode($part["content"]) to retrieve its data.
If a message is not multipart, its contents are placed into the “content” field of the associative array.
There may be additional undocumented fields in the array. Use print_r(parse_mbox(…)) to see it all, if you’re brave.
Download: The One and Only Version
License: This script is hereby declared public domain. Use it for any purpose you please, and modify it in any way you desire. Any modifications, however, must not be attributed to me, nor should any modified version be expected to work in the same way as the original provided here.
Disclaimer: I take no responsibility for anything that might happen as a result of using this script. By using it, you’re agreeing that no consequence of its use is my responsibility. Furthermore, I make no guarantee of the accuracy of any information returned by any functions therein.
Leave a comment
You must be logged in to post a comment.