tags:

views:

343

answers:

4

I'm extracting emails from a database where they're stored as strings. I need to parse these emails to extract their attachments. I guess there must already be some library to do this easily but I can't find any.

+1  A: 

This could be done using the Zend_Mail component of the Zend Framework

Maybe this example, which can also be found in the documentation helps:

// get the first none multipart part
$part = $message;
while ($part->isMultipart()) {
    $part = $message->getPart(1);
}
echo 'Type of this part is ' . strtok($part->contentType, ';') . "\n";
echo "Content:\n";
echo $part->getContent();

I don't know however how you can tell Zend Mail to read from strings, maybe there's some work required to do this, but then you'd have a full-fletched library that does what you want and some more(like reading the subject, etc.).

Edit:

I just had a second look at it and realized that all you have to do is write an own storage implementation(subclass Zend_Mail_Storage_Abstract) which shouldn't be so hard to do.

I think that's the cleanest solution you'll get, albeit a little effort is required to make it work.

If you're looking for a more quick'n'dirty kind of solution someone else might be able to help you.

Hope that helps.

André Hoffmann
+2  A: 

PEAR::Mail::mimeDecode should do what you're looking for

Mez
Thanks, exactly what I needed.
Arkh
A: 

E-mail attachments are MIME encoded and added to the message body using headers. The PEAR MIME decode package will do what you need: http://pear.php.net/package/Mail_mimeDecode

Al
A: 

PHP has a MailParse extension that is a lot faster then using the PEAR alternative which is native PHP.

Here is a library that wraps this extension:

http://code.google.com/p/php-mime-mail-parser/

Example:

// require mime parser library
require_once('MimeMailParser.class.php');

// instantiate the mime parser
$Parser = new MimeMailParser();

// set the email text for parsing
$Parser->setText($text);

// get attachments
$attachments = $Parser->getAttachments();
bucabay