Forum Moderators: coopster

Message Too Old, No Replies

parsing email with PHP, and saving attachments

anyone know of a quickie solution?

         

httpwebwitch

11:59 pm on Jun 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have this situation where I'm receiving an email as a string. Headers, Body, attachments - it's all raw, saved as one big long string.

These email messages have attachments. I need to save these attachments as a file, and also keep the contents of the file as a string so they can be processed further (that's the next challenge after this one)

I can see these attachments nestled comfortably in the body of the email:

--_1f366895-b327-4f84-8985-e3826cdf604b_
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="namechangedtoprotecttheinnocent.zip"
UEsFBBQACAAIAJuy1DgAAAAAAAAAAAAAAAAKAAAAcmVwb3J0LnhtbNVdW5fbNpJ+n1/B9Z6zb8Mh
rgTPJplGt9N2HNvxiTPjM/vGltjdinUbUrLT+fVLUqJEUKSAYoE0p+10YkIdfwCBQl2+qvru73+s
lt6XJM0Dm/X3z4gfPPOyXbyex8vNOvn+2VOSPfv7D3/5y3dpst2kux++28V3y+SH72ab5X61zqr/
8NbxKv/0PN4Dz3747m+Hh43BWbzaxouHdecH4vlDutlvO8c/J09fN+m8e/zryyTb/SNddn5isdpm

... and so on.

Does anyone know any good pre-rolled classes that will aid in doing this effectively?

The idea of parsing and slicing up these emails manually is a little frightening, because I know it means more hours of frustration on a project which was supposed to be quick + dirty

coopster

3:07 pm on Jun 23, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



The best I might offer would be to parse the string with a regular expression or perhaps investigate the Mail Related Extensions [php.net]. No quickie solutions available. How are you getting the string in this format in the first place? If it is via the imap functions couldn't your parse it with more of the imap functions?

cameraman

5:48 pm on Jun 23, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I don't know of any pre-rolled classes, but you may be trying to overthink it and make it harder than it is.
1. Read the email's content-type header to get the boundary marker
2. use the boundary marker as an argument to explode()
3. look at the array elements to find the octet-stream
4. strip the section 'headers' from it
5. base64_decode it
6. save the decoded string as a file

httpwebwitch

2:47 pm on Jun 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Eureka!
I discovered the IMAP functions [php.net] in PHP5!

I'm taking a step back, and using those to retrieve mail instead of what I was using before... it's working great! I can grab attachments, save them as files, then immediately read those files back into a string. I know it involves 2 I/O (write, then read) instead of 1 (just write), but it's fast enough for me.