Using Zend to parse raw SMTP email data

I needed to create a script today that takes raw SMTP input from stdin. The project is running on Zend and they have a library for email. However, their documentation is geared toward getting that email from a mailserver. As far as I could find there wasn’t an example of how to create an email object out of the raw SMTP data.

Create a Zend_Mail_Message from the raw string.

$email = new Zend_Mail_Message(array('raw' => $email_str));

To grab the subject:

$email->subject;

All I wanted was the body from the text/plain piece of the email. If you’ve got a multi-part message it’s a little tricky. Here’s what I compiled from Zend’s documentation:

if($email->isMultipart()) {
  foreach (new RecursiveIteratorIterator($email) as $part) {
    try {
      if (strtok($part->contentType, ';') == 'text/plain') {
        $body = trim($part);
        break;
      }
    } catch (Zend_Mail_Exception $e) { // ignore }
  }
  if(!$body) {
    //Error
  }
} else {
  $body = trim($email->getContent());
}

Tags: , , , , , ,

3 Comments on “Using Zend to parse raw SMTP email data”

  1. roberto Says:

    hey just wondering where the getContent() method is coming from? is it one you created or part of the Zend framework?

  2. dmertl Says:

    Had a bug in the code sample there, should’ve been $email->getContent(). And yeah, getContent is part of Zend_Mail_Message. Grabs the content of the message if it’s not multi-part. If you want more info, check out http://framework.zend.com/manual/en/zend.mail.read.html#zend.mail.read-message

  3. roberto Says:

    Thank you this example was very useful for my project

Leave a Comment