17.14. Reading Mail Messages
Prev | Chapter 17. Zend_Mail | Next

## 17.14. Reading Mail Messages

`Zend_Mail` can read mail messages from several local or remote mail storages. All of them have the same basic API to count and fetch messages and some of them implement additional interfaces for not so common features. For a feature overview of the implemented storages see the following table.

Table 17.1. Mail Read Feature Overview

Feature | Mbox | Maildir | Pop3 | IMAP
--- | --- | --- | --- | ---
Storage type | local | local | remote | remote
Fetch message | Yes | Yes | Yes | Yes
Fetch mime-part | emulated | emulated | emulated | emulated
Folders | Yes | Yes | No | Yes
Create message/folder | No | todo | No | todo
Flags | No | todo | No | todo

### 17.14.1. Simple example using Pop3

    <?php
    $mail = new Zend_Mail_Storage_Pop3(array('host'     => 'localhost',
                                             'user'     => 'test',
                                             'password' => 'test'));

    echo $mail->countMessages() . " messages found\n";
    foreach ($mail as $message) {
        echo "Mail from '{$message->from}': {$message->subject}\n";
    }

### 17.14.2. Opening a local storage

Mbox and Maildir are the two supported formats for local mail storages, both in their most simple formats.

If you want to read from a Mbox file you only need to give the filename to the constructor of `Zend_Mail_Storage_Mbox`:

    <?php
    $mail = new Zend_Mail_Storage_Mbox(array('filename' => '/home/test/mail/inbox'));

Maildir is very similar but needs a dirname:

    <?php
    $mail = new Zend_Mail_Storage_Maildir(array('dirname' => '/home/test/mail/'));

Both constructors throw a `Zend_Mail_Exception` if the storage can't be read.

### 17.14.3. Opening a remote storage

For remote storages the two most popular protocols are supported: Pop3 and Imap. Both need at least a host and a user to connect and login. The default password is an empty string, the default port as given in the protocol RFC.

    <?php
    // connecting with Pop3
    $mail = new Zend_Mail_Storage_Pop3(array('host'     => 'example.com'
                                             'user'     => 'test',
                                             'password' => 'test'));

    // connecting with Imap
    $mail = new Zend_Mail_Storage_Imap(array('host'     => 'example.com'
                                             'user'     => 'test',
                                             'password' => 'test'));

    // example for a none standard port
    $mail = new Zend_Mail_Storage_Pop3(array('host'     => 'example.com',
                                             'port'     => 1120
                                             'user'     => 'test',
                                             'password' => 'test'));

For both storages SSL and TLS are supported. If you use SSL the default port changes as given in the RFC.

    <?php
    // examples for Zend_Mail_Storage_Pop3, same works for Zend_Mail_Storage_Imap

    // use SSL on different port (default is 995 for Pop3 and 993 for Imap)
    $mail = new Zend_Mail_Storage_Pop3(array('host'     => 'example.com'
                                             'user'     => 'test',
                                             'password' => 'test',
                                             'ssl'      => 'SSL'));

    // use TLS
    $mail = new Zend_Mail_Storage_Pop3(array('host'     => 'example.com'
                                             'user'     => 'test',
                                             'password' => 'test',
                                             'ssl'      => 'TLS'));

Both constructors can throw `Zend_Mail_Exception` or `Zend_Mail_Protocol_Exception` (extends `Zend_Mail_Exception`), depending on the type of error.

### 17.14.4. Fetching messages and simple methods

Once you've opened the storage messages can be fetched. You need the message number, which is a counter starting with 1 for the first message. To fetch the message you use the method `getMessage()`:

    <?php
    $message = $mail->getMessage($messageNum);

Array access is also supported, but won't supported any additional parameters that could be added to `getMessage()`. As long as you don't mind and can live with defaults you may use:

    <?php
    $message = $mail[$messageNum];

For iterating over all messages the Iterator interface is implemented:

    <?php
    foreach ($mail as $messageNum => $message) {
        // do stuff ...
    }

To count the messages in the storage you can either use the method `countMessages()` or use array access:

    <?php
    // method
    $maxMessage = $mail->countMessages();

    // array access
    $maxMessage = count($mail);

To remove a mail you use the method `removeMessage()` or again array access:

    <?php
    // method
    $mail->removeMessage($messageNum);

    // array access
    unset($mail[$messageNum]);

### 17.14.5. Working with messages

After you fetched the messages with `getMessage()` you want to fetch headers, the content or single parts of a multipart message. All headers can be accessed via properties or the method `getHeader()` if you want more control or have unusual header names. The header names are lower-cased internally, thus the case of the header name in the mail message doesn't matter. Also headers with a dash can be written in camel-case.

    <?php
    // get the message object
    $message = $mail->getMessage(1);

    // output subject of message
    echo $message->subject . "\n";

    // get content-type header
    $type = $message->contentType;

If you have multiple headers with the same name i.e. the Received headers you might want it as array instead of a string, which is possible with the `getHeader()` method.

    <?php
    // get header as property - the result is always a string, with new lines between the single occurrences in the message
    $received = $message->received;

    // the same via getHeader() method
    $received = $message->getHeader('received', 'string');

    // better an array with a single entry for every occurrences
    $received = $message->getHeader('received', 'array');
    foreach ($received as $line) {
        // do stuff
    }

    // if you don't define a format you'll get the internal representation (string for single headers, array for multiple)
    $received = $message->getHeader('received');
    if (is_string($received)) {
        // only one received header found in message
    }

The method `getHeaders()` returns all headers as array with the lower-cased name as key and the value as array for multiple headers or as string for single headers.

    <?php
    // dump all headers
    foreach ($message->getHeaders as $name => $value) {
        if (is_string($value)) {
            echo "$name: $value\n";
            continue;
        }
        foreach ($value as $entry) {
            echo "$name: $entry\n";
        }
    }

If you don't have a multipart message fetching the content is easy done via `getContent()`. Unlike the headers the content is only fetched when needed (aka late-fetch).

    <?php
    // output message content for HTML
    echo '<pre>';
    echo $message->getContent();
    echo '</pre>';

Checking for a multipart message is done with the method `isMultipart()`. If you have multipart message you can get an instance of `Zend_Mail_Part` with the method `getPart()`. `Zend_Mail_Part` is the base class of `Zend_Mail_Message`, so you have the same methods: `getHeader()`, `getHeaders()`, `getContent()`, `getPart()`, `isMultipart` and the properties for headers.

    <?php
    // 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();

Zend_Mail_Part also implements RecursiveIterator, which makes it easy to scan through all parts. And for easy output it also implements the magic method __toString(), which returns the content.

    <?php
    // output first text/plain part
    $foundPart = null;
    foreach (RecursiveIteratorIterator($mail->getMessage(1)) as $part) {
        try {
            if (strtok($part->contentType, ';') == 'text/plain') {
                $foundPart = $part;
                break;
            }
        } catch (Zend_Mail_Exception $e) {
            // ignore
        }
    }
    if (!$foundPart) {
        echo 'no plain text part found';
    } else {
        echo "plain text part: \n" . $foundPart;
    }

### 17.14.6. Using folders

All storages, except Pop3, support folders, also called mailboxes. The interface implemented by all storages supporting folders is called `Zend_Mail_Storage_Folder_Interface`. Also all of these classes have an additional optional parameter called folder, which is the folder selected after login, in the constructor.

For the local storages you need to use separate classes called `Zend_Mail_Storage_Folder_Mbox` or `Zend_Mail_Storage_Folder_Maildir`. Both need one parameter called dirname with the name of the base dir. The format for maildir is as defined in maildir++ (with a dot as default delimiter), Mbox is a directory hierarchy with Mbox files. If you don't have a Mbox file called INBOX in your Mbox base dir you need to set an other folder in the constructor.

`Zend_Mail_Storage_Imap` already supports folders by default. Examples for opening these storages:

    <?php
    // mbox with folders
    $mail = new Zend_Mail_Storage_Folder_Mbox(array('dirname' => '/home/test/mail/'));

    // mbox with a default folder not called INBOX, also works
    // with Zend_Mail_Storage_Folder_Maildir and Zend_Mail_Storage_Imap
    $mail = new Zend_Mail_Storage_Folder_Mbox(array('dirname' => '/home/test/mail/',
                                                    'folder'  => 'Archive'));

    // maildir with folders
    $mail = new Zend_Mail_Storage_Folder_Maildir(array('dirname' => '/home/test/mail/'));

    // maildir with colon as delimiter, as suggested in Maildir++
    $mail = new Zend_Mail_Storage_Folder_Maildir(array('dirname' => '/home/test/mail/'
                                                       'delim'   => ':'));

    // imap is the same with and without folders
    $mail = new Zend_Mail_Storage_Imap(array('host'     => 'example.com'
                                             'user'     => 'test',
                                             'password' => 'test'));

With the method getFolders($root = null) you can get the folder hierarchy starting with the root folder or the given folder. It's returned as instance of `Zend_Mail_Storage_Folder`, which implements `RecursiveIterator` and all children are also instances of `Zend_Mail_Storage_Folder`. Each of these instances has a local and a global name returned by the methods `getLocalName()` and `getGlobalName()`. The global name is the absolute name from the root folder (including delimiters), the local name is the name in the parent folder.

Table 17.2. Mail Folder Names

Global Name | Local Name
--- | ---
/INBOX | INBOX
/Archive/2005 | 2005
List.ZF.General | General

If you use the iterator the key of the current element is the local name. The global name is also returned by the magic method `__toString()`. Some folders may not be selectable, which means they can't store messages and selecting them results in an error. This can be checked with the method `isSelectable()`. So it's very easy to output the whole tree in a view:

    <?php
    $folders = new RecursiveIteratorIterator($this->mail->getFolders(),
                                             RecursiveIteratorIterator::SELF_FIRST);
    echo '<select name="folder">';
    foreach ($folders as $localName => $folder) {
        $localName = str_pad('', $folders->getDepth(), '-', STR_PAD_LEFT) . $localName;
        echo '<option';
        if (!$folder->isSelectable()) {
            echo ' disabled="disabled"';
        }
        echo ' value="' . htmlspecialchars($folder) . '">'
            . htmlspecialchars($localName) . '</option>';
    }
    echo '</select>';

The current selected folders is returned by the method `getSelectedFolder()`. Changing the folder is done with the method `selectFolder()`, which needs the global name as parameter. If you want to avoid to write delimiters you can also use the properties of a `Zend_Mail_Storage_Folder` instance:

    <?php
    // depending on your mail storage and its settings $rootFolder->Archive->2005
    // is the same as:
    //   /Archive/2005
    //  Archive:2005
    //  INBOX.Archive.2005
    //  ...
    $folder = $mail->getFolders()->Archive->2005;
    echo 'Last folder was ' . $mail->getSelectedFolder() . "new folder is $folder\n";
    $mail->selectFolder($folder);

### 17.14.7. Advanced Use

#### 17.14.7.1. Using NOOP

If you're using a remote storage and have some long tasks you might need to keep the connection alive via noop:

    <?php
    foreach ($mail as $message) {

        // do some calculations ...

        $mail->noop(); // keep alive

        // do something else ...

        $mail->noop(); // keep alive
    }

#### 17.14.7.2. Caching instances

`Zend_Mail_Storage_Mbox`, `Zend_Mail_Storage_Folder_Mbox`, `Zend_Mail_Storage_Maildir` and `Zend_Mail_Storage_Folder_Maildir` implement the magic methods `__sleep()` and `__wakeup()`, which means they are serializable. This avoids parsing the files or directory tree more than once. The disadvantage is that your Mbox or Maildir storage should not change. Some easy checks are done, like reparsing the current Mbox file if the modification time changes or reparsing the folder structure if a folder has vanished (which still results in an error, but you can search for an other folder afterwards). It's better if you have something like a signal file for changes and check it before using the cached instance.

    <?php
    // there's no specific cache handler/class used here,
    // change the code to match your cache handler
    $signal_file = '/home/test/.mail.last_change';
    $mbox_basedir = '/home/test/mail/';
    $cache_id = 'example mail cache ' . $mbox_basedir . $signal_file;

    $cache = new Your_Cache_Class();
    if (!$cache->isCached($cache_id) || filemtime($signal_file) > $cache->getMTime($cache_id)) {
        $mail = new Zend_Mail_Storage_Folder_Pop3(array('dirname' => $mbox_basedir));
    } else {
        $mail = $cache->get($cache_id);
    }

    // do stuff ...

    $cache->set($cache_id, $mail);

#### 17.14.7.3. Extending Protocol Classes

Remote storages use two classes: `Zend_Mail_Storage_<Name>` and `Zend_Mail_Protocol_<Name>`. The protocol class translates the protocol commands and responses from and to PHP, like methods for the commands or variables with different structures for data. The other/main class implements the common interface.

If you need additional protocol features you can extend the protocol class and use it in the constructor of the main class. As an example assume we need to knock different ports before we can connect to POP3.

    <?php
    require_once 'Zend.php';
    Zend::loadClass('Zend_Mail_Storage_Pop3');

    class Example_Mail_Exception extends Zend_Mail_Exception
    {
    }

    class Example_Mail_Protocol_Exception extends Zend_Mail_Protocol_Exception
    {
    }

    class Example_Mail_Protocol_Pop3_Knock extends Zend_Mail_Protocol_Pop3
    {
        private $host, $port;

        public function __construct($host, $port = null)
        {
            // no auto connect in this class
            $this->host = $host;
            $this->port = $port;
        }

        public function knock($port)
        {
            $sock = @fsockopen($this->host, $port);
            if ($sock) {
                fclose($sock);
            }
        }

        public function connect($host = null, $port = null, $ssl = false)
        {
            if ($host === null) {
                $host = $this->host;
            }
            if ($port === null) {
                $port = $this->port;
            }
            parent::connect($host, $port);
        }
    }

    class Example_Mail_Pop3_Knock extends Zend_Mail_Storage_Pop3
    {
        public function __construct(array $params)
        {
            // ... check $params here! ...
            $protocol = new Example_Mail_Protocol_Pop3_Knock($params['host']);

            // do our "special" thing
            foreach ((array)$params['knock_ports'] as $port) {
                $protocol->knock($port);
            }

            // get to correct state
            $protocol->connect($params['host'], $params['port']);
            $protocol->login($params['user'], $params['password']);

            // initialize parent
            parent::__construct($protocol);
        }
    }

    $mail = new Example_Mail_Pop3_Knock(array('host'        => 'localhost',
                                              'user'        => 'test',
                                              'password'    => 'test',
                                              'knock_ports' => array(1101, 1105, 1111)));

As you see we always assume we're connected, logged in and, if supported, a folder is selected in the constructor of the main class. Thus if you assign your own protocol class you always need to make sure that's done or the next method will fail if the server doesn't allow it in the current state.

Prev | Up | Next
17.13. Securing SMTP Transport | Home | Chapter 18. Zend_Measure