tags:

views:

993

answers:

4

As a "look under the covers" tutorial for myself I am building a PHP script to gather emails from a POP3 mailbox. While attempting to make use of binary attachments I am stuck trying to figure out what to do with the attachment information.

Given a string that would be gathered from an email:

------=_Part_16735_17392833.1229653992102 Content-Type: image/jpeg; name=trans2.jpg Content-Transfer-Encoding: base64 X-Attachment-Id: f_fow87t5j0 Content-Disposition: attachment; filename=trans2.jpg

/9j/4AAQSkZJRgABAgEASABIAAD/4QxrRXhpZgAATU0AKgAAAAgABwESAAMAAAABAAEAAAEaAAUA AAABAAAAYgEbAAUAAAABAAAAagEoAAMAAAABAAIAAAExAAIAAAAUAAAAcgEyAAIAAAAUAAAAhodp

(...)

EAgEAgEAgEAgEAg8IBQRL/Lbe/tJrScHqZ2lkmE4XUP2XcSDZZ2VvZ28dtbsDIYmhkbRxAIJCAQC AQCAQf/ScyAQCAQCAQCAQCAQCAQCAQCAQCAQCAQf/9k= ------=_Part_16735_17392833.1229653992102--

Is there a way to save off the data to disk so that it would be in a usable format?

A: 

chop off first and last line, base64decode and save under given filename.

done.

smartcoder
+4  A: 

Pass the data to base64_decode() to get the binary data, write it out to a file with file_put_contents()

Paul Dixon
A: 

While reinventing the wheel has some entertainment and educational value, I would try to resist the temptation: Mailparse, Mail_mimeDecode

Milen A. Radev
+1  A: 

If you have a lot of data to write out that needs to be decoded before writing I would suggest using stream filters so decode the data as you write it...

$fh = fopen('where_you_are_writing', 'wb');
stream_filter_append($fh, 'convert.base64-decode');

// Do a lot of writing here. It will be automatically decoded from base64.

fclose($h);
Mike Boers