1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.mail.read">
4 <title>Reading Mail Messages</title>
7 <classname>Zend_Mail</classname> can read mail messages from several local or remote mail
8 storages. All of them have the same basic <acronym>API</acronym> to count and fetch messages
9 and some of them implement additional interfaces for not so common features. For a feature
10 overview of the implemented storages, see the following table.
13 <table id="zend.mail.read.table-1">
14 <title>Mail Read Feature Overview</title>
19 <entry>Feature</entry>
21 <entry>Maildir</entry>
23 <entry><constant>IMAP</constant></entry>
29 <entry>Storage type</entry>
37 <entry>Fetch message</entry>
45 <entry>Fetch <acronym>MIME</acronym>-part</entry>
46 <entry>emulated</entry>
47 <entry>emulated</entry>
48 <entry>emulated</entry>
49 <entry>emulated</entry>
53 <entry>Folders</entry>
61 <entry>Create message/folder</entry>
87 <sect2 id="zend.mail.read-example">
88 <title>Simple example using Pop3</title>
90 <programlisting language="php"><![CDATA[
91 $mail = new Zend_Mail_Storage_Pop3(array('host' => 'localhost',
93 'password' => 'test'));
95 echo $mail->countMessages() . " messages found\n";
96 foreach ($mail as $message) {
97 echo "Mail from '{$message->from}': {$message->subject}\n";
102 <sect2 id="zend.mail.read-open-local">
103 <title>Opening a local storage</title>
106 Mbox and Maildir are the two supported formats for local mail storages, both in their
111 If you want to read from a Mbox file you only need to give the filename to the
112 constructor of <classname>Zend_Mail_Storage_Mbox</classname>:
115 <programlisting language="php"><![CDATA[
116 $mail = new Zend_Mail_Storage_Mbox(array('filename' =>
117 '/home/test/mail/inbox'));
120 <para>Maildir is very similar but needs a dirname:</para>
122 <programlisting language="php"><![CDATA[
123 $mail = new Zend_Mail_Storage_Maildir(array('dirname' =>
124 '/home/test/mail/'));
128 Both constructors throw a <classname>Zend_Mail_Exception</classname> if the storage
133 <sect2 id="zend.mail.read-open-remote">
134 <title>Opening a remote storage</title>
137 For remote storages the two most popular protocols are supported: Pop3 and Imap. Both
138 need at least a host and a user to connect and login. The default password is an empty
139 string, the default port as given in the protocol <acronym>RFC</acronym>.
142 <programlisting language="php"><![CDATA[
143 // connecting with Pop3
144 $mail = new Zend_Mail_Storage_Pop3(array('host' => 'example.com',
146 'password' => 'test'));
148 // connecting with Imap
149 $mail = new Zend_Mail_Storage_Imap(array('host' => 'example.com',
151 'password' => 'test'));
153 // example for a none standard port
154 $mail = new Zend_Mail_Storage_Pop3(array('host' => 'example.com',
157 'password' => 'test'));
161 For both storages <acronym>SSL</acronym> and TLS are supported. If you use
162 <acronym>SSL</acronym> the default port changes as given in the <acronym>RFC</acronym>.
165 <programlisting language="php"><![CDATA[
166 // examples for Zend_Mail_Storage_Pop3, same works for Zend_Mail_Storage_Imap
168 // use SSL on different port (default is 995 for Pop3 and 993 for Imap)
169 $mail = new Zend_Mail_Storage_Pop3(array('host' => 'example.com',
171 'password' => 'test',
175 $mail = new Zend_Mail_Storage_Pop3(array('host' => 'example.com',
177 'password' => 'test',
182 Both constructors can throw <classname>Zend_Mail_Exception</classname> or
183 <classname>Zend_Mail_Protocol_Exception</classname> (extends
184 <classname>Zend_Mail_Exception</classname>), depending on the type of error.
188 <sect2 id="zend.mail.read-fetching">
189 <title>Fetching messages and simple methods</title>
192 Messages can be fetched after you've opened the storage . You need the message number,
193 which is a counter starting with 1 for the first message. To fetch the message, you use
194 the method <methodname>getMessage()</methodname>:
197 <programlisting language="php"><![CDATA[
198 $message = $mail->getMessage($messageNum);
202 Array access is also supported, but this access method won't supported any additional
203 parameters that could be added to <methodname>getMessage()</methodname>. As long as you
204 don't mind, and can live with the default values, you may use:
207 <programlisting language="php"><![CDATA[
208 $message = $mail[$messageNum];
211 <para>For iterating over all messages the Iterator interface is implemented:</para>
213 <programlisting language="php"><![CDATA[
214 foreach ($mail as $messageNum => $message) {
220 To count the messages in the storage, you can either use the method
221 <methodname>countMessages()</methodname> or use array access:
224 <programlisting language="php"><![CDATA[
226 $maxMessage = $mail->countMessages();
229 $maxMessage = count($mail);
233 To remove a mail, you use the method <methodname>removeMessage()</methodname> or again
237 <programlisting language="php"><![CDATA[
239 $mail->removeMessage($messageNum);
242 unset($mail[$messageNum]);
246 <sect2 id="zend.mail.read-message">
247 <title>Working with messages</title>
250 After you fetch the messages with <methodname>getMessage()</methodname> you want to
251 fetch headers, the content or single parts of a multipart message. All headers can be
252 accessed via properties or the method <methodname>getHeader()</methodname> if you want
253 more control or have unusual header names. The header names are lower-cased internally,
254 thus the case of the header name in the mail message doesn't matter. Also headers with a
255 dash can be written in camel-case. If no header is found for both notations an exception
256 is thrown. To encounter this the method <methodname>headerExists()</methodname> can be
257 used to check the existence of a header.
260 <programlisting language="php"><![CDATA[
261 // get the message object
262 $message = $mail->getMessage(1);
264 // output subject of message
265 echo $message->subject . "\n";
267 // get content-type header
268 $type = $message->contentType;
270 // check if CC isset:
271 if( isset($message->cc) ) { // or $message->headerExists('cc');
277 If you have multiple headers with the same name- i.e. the Received headers- you might
278 want an array instead of a string. In this case, use the
279 <methodname>getHeader()</methodname> method.
282 <programlisting language="php"><![CDATA[
283 // get header as property - the result is always a string,
284 // with new lines between the single occurrences in the message
285 $received = $message->received;
287 // the same via getHeader() method
288 $received = $message->getHeader('received', 'string');
290 // better an array with a single entry for every occurrences
291 $received = $message->getHeader('received', 'array');
292 foreach ($received as $line) {
296 // if you don't define a format you'll get the internal representation
297 // (string for single headers, array for multiple)
298 $received = $message->getHeader('received');
299 if (is_string($received)) {
300 // only one received header found in message
305 The method <methodname>getHeaders()</methodname> returns all headers as array with the
306 lower-cased name as key and the value as and array for multiple headers or as string for
310 <programlisting language="php"><![CDATA[
312 foreach ($message->getHeaders() as $name => $value) {
313 if (is_string($value)) {
314 echo "$name: $value\n";
317 foreach ($value as $entry) {
318 echo "$name: $entry\n";
324 If you don't have a multipart message, fetching the content is easily done via
325 <methodname>getContent()</methodname>. Unlike the headers, the content is only fetched
326 when needed (aka late-fetch).
329 <programlisting language="php"><![CDATA[
330 // output message content for HTML
332 echo $message->getContent();
337 Checking for multipart messages is done with the method
338 <methodname>isMultipart()</methodname>. If you have multipart message you can get an
339 instance of <classname>Zend_Mail_Part</classname> with the method
340 <methodname>getPart()</methodname>. <classname>Zend_Mail_Part</classname> is the base
341 class of <classname>Zend_Mail_Message</classname>, so you have the same methods:
342 <methodname>getHeader()</methodname>, <methodname>getHeaders()</methodname>,
343 <methodname>getContent()</methodname>, <methodname>getPart()</methodname>,
344 <code>isMultipart</code> and the properties for headers.
347 <programlisting language="php"><![CDATA[
348 // get the first none multipart part
350 while ($part->isMultipart()) {
351 $part = $message->getPart(1);
353 echo 'Type of this part is ' . strtok($part->contentType, ';') . "\n";
355 echo $part->getContent();
359 <classname>Zend_Mail_Part</classname> also implements <code>RecursiveIterator</code>,
360 which makes it easy to scan through all parts. And for easy output, it also implements
361 the magic method <methodname>__toString()</methodname>, which returns the content.
364 <programlisting language="php"><![CDATA[
365 // output first text/plain part
367 foreach (new RecursiveIteratorIterator($mail->getMessage(1)) as $part) {
369 if (strtok($part->contentType, ';') == 'text/plain') {
373 } catch (Zend_Mail_Exception $e) {
378 echo 'no plain text part found';
380 echo "plain text part: \n" . $foundPart;
385 <sect2 id="zend.mail.read-flags">
386 <title>Checking for flags</title>
389 Maildir and IMAP support storing flags. The class
390 <classname>Zend_Mail_Storage</classname> has constants for all known maildir and IMAP
391 system flags, named <classname>Zend_Mail_Storage::FLAG_<flagname></classname>. To
392 check for flags <classname>Zend_Mail_Message</classname> has a method called
393 <methodname>hasFlag()</methodname>. With <methodname>getFlags()</methodname> you'll get
397 <programlisting language="php"><![CDATA[
398 // find unread messages
399 echo "Unread mails:\n";
400 foreach ($mail as $message) {
401 if ($message->hasFlag(Zend_Mail_Storage::FLAG_SEEN)) {
404 // mark recent/new mails
405 if ($message->hasFlag(Zend_Mail_Storage::FLAG_RECENT)) {
410 echo $message->subject . "\n";
413 // check for known flags
414 $flags = $message->getFlags();
415 echo "Message is flagged as: ";
416 foreach ($flags as $flag) {
418 case Zend_Mail_Storage::FLAG_ANSWERED:
421 case Zend_Mail_Storage::FLAG_FLAGGED:
426 // check for other flags
430 echo $flag . '(unknown flag) ';
436 As IMAP allows user or client defined flags, you could get flags that don't have a
437 constant in <classname>Zend_Mail_Storage</classname>. Instead, they are returned as
438 strings and can be checked the same way with <methodname>hasFlag()</methodname>.
441 <programlisting language="php"><![CDATA[
442 // check message for client defined flags $IsSpam, $SpamTested
443 if (!$message->hasFlag('$SpamTested')) {
444 echo 'message has not been tested for spam';
445 } else if ($message->hasFlag('$IsSpam')) {
446 echo 'this message is spam';
448 echo 'this message is ham';
453 <sect2 id="zend.mail.read-folders">
454 <title>Using folders</title>
457 All storages, except Pop3, support folders, also called mailboxes. The interface
458 implemented by all storages supporting folders is called
459 <classname>Zend_Mail_Storage_Folder_Interface</classname>. Also all of these classes
460 have an additional optional parameter called <code>folder</code>, which is the folder
461 selected after login, in the constructor.
465 For the local storages you need to use separate classes called
466 <classname>Zend_Mail_Storage_Folder_Mbox</classname> or
467 <classname>Zend_Mail_Storage_Folder_Maildir</classname>. Both need one parameter called
468 <code>dirname</code> with the name of the base dir. The format for maildir is as defined
469 in maildir++ (with a dot as default delimiter), Mbox is a directory hierarchy with Mbox
470 files. If you don't have a Mbox file called INBOX in your Mbox base dir you need to set
471 another folder in the constructor.
475 <classname>Zend_Mail_Storage_Imap</classname> already supports folders by default.
476 Examples for opening these storages:
479 <programlisting language="php"><![CDATA[
481 $mail = new Zend_Mail_Storage_Folder_Mbox(array('dirname' =>
482 '/home/test/mail/'));
484 // mbox with a default folder not called INBOX, also works
485 // with Zend_Mail_Storage_Folder_Maildir and Zend_Mail_Storage_Imap
486 $mail = new Zend_Mail_Storage_Folder_Mbox(array('dirname' =>
491 // maildir with folders
492 $mail = new Zend_Mail_Storage_Folder_Maildir(array('dirname' =>
493 '/home/test/mail/'));
495 // maildir with colon as delimiter, as suggested in Maildir++
496 $mail = new Zend_Mail_Storage_Folder_Maildir(array('dirname' =>
500 // imap is the same with and without folders
501 $mail = new Zend_Mail_Storage_Imap(array('host' => 'example.com',
503 'password' => 'test'));
507 With the method getFolders($root = null) you can get the folder hierarchy starting with
508 the root folder or the given folder. It's returned as an instance of
509 <classname>Zend_Mail_Storage_Folder</classname>, which implements
510 <code>RecursiveIterator</code> and all children are also instances of
511 <classname>Zend_Mail_Storage_Folder</classname>. Each of these instances has a local and
512 a global name returned by the methods <methodname>getLocalName()</methodname> and
513 <methodname>getGlobalName()</methodname>. The global name is the absolute name from the
514 root folder (including delimiters), the local name is the name in the parent folder.
517 <table id="zend.mail.read-folders.table-1">
518 <title>Mail Folder Names</title>
523 <entry>Global Name</entry>
524 <entry>Local Name</entry>
530 <entry>/INBOX</entry>
535 <entry>/Archive/2005</entry>
540 <entry>List.ZF.General</entry>
541 <entry>General</entry>
548 If you use the iterator, the key of the current element is the local name. The global
549 name is also returned by the magic method <methodname>__toString()</methodname>. Some
550 folders may not be selectable, which means they can't store messages and selecting them
551 results in an error. This can be checked with the method
552 <methodname>isSelectable()</methodname>. So it's very easy to output the whole tree in a
556 <programlisting language="php"><![CDATA[
557 $folders = new RecursiveIteratorIterator($this->mail->getFolders(),
558 RecursiveIteratorIterator::SELF_FIRST);
559 echo '<select name="folder">';
560 foreach ($folders as $localName => $folder) {
561 $localName = str_pad('', $folders->getDepth(), '-', STR_PAD_LEFT) .
564 if (!$folder->isSelectable()) {
565 echo ' disabled="disabled"';
567 echo ' value="' . htmlspecialchars($folder) . '">'
568 . htmlspecialchars($localName) . '</option>';
574 The current selected folder is returned by the method
575 <methodname>getSelectedFolder()</methodname>. Changing the folder is done with the
576 method <methodname>selectFolder()</methodname>, which needs the global name as
577 parameter. If you want to avoid to write delimiters you can also use the properties of a
578 <classname>Zend_Mail_Storage_Folder</classname> instance:
581 <programlisting language="php"><![CDATA[
582 // depending on your mail storage and its settings $rootFolder->Archive->2005
586 // INBOX.Archive.2005
588 $folder = $mail->getFolders()->Archive->2005;
589 echo 'Last folder was '
590 . $mail->getSelectedFolder()
591 . "new folder is $folder\n";
592 $mail->selectFolder($folder);
596 <sect2 id="zend.mail.read-advanced">
597 <title>Advanced Use</title>
599 <sect3 id="zend.mail.read-advanced.noop">
600 <title>Using NOOP</title>
603 If you're using a remote storage and have some long tasks you might need to keep
604 the connection alive via noop:
607 <programlisting language="php"><![CDATA[
608 foreach ($mail as $message) {
610 // do some calculations ...
612 $mail->noop(); // keep alive
614 // do something else ...
616 $mail->noop(); // keep alive
621 <sect3 id="zend.mail.read-advanced.caching">
622 <title>Caching instances</title>
625 <classname>Zend_Mail_Storage_Mbox</classname>,
626 <classname>Zend_Mail_Storage_Folder_Mbox</classname>,
627 <classname>Zend_Mail_Storage_Maildir</classname> and
628 <classname>Zend_Mail_Storage_Folder_Maildir</classname> implement the magic methods
629 <methodname>__sleep()</methodname> and <methodname>__wakeup()</methodname>, which
630 means they are serializable. This avoids parsing the files or directory tree more
631 than once. The disadvantage is that your Mbox or Maildir storage should not change.
632 Some easy checks may be done, like reparsing the current Mbox file if the
633 modification time changes, or reparsing the folder structure if a folder has
634 vanished (which still results in an error, but you can search for another folder
635 afterwards). It's better if you have something like a signal file for changes and
636 check it before using the cached instance.
639 <programlisting language="php"><![CDATA[
640 // there's no specific cache handler/class used here,
641 // change the code to match your cache handler
642 $signal_file = '/home/test/.mail.last_change';
643 $mbox_basedir = '/home/test/mail/';
644 $cache_id = 'example mail cache ' . $mbox_basedir . $signal_file;
646 $cache = new Your_Cache_Class();
647 if (!$cache->isCached($cache_id) ||
648 filemtime($signal_file) > $cache->getMTime($cache_id)) {
649 $mail = new Zend_Mail_Storage_Folder_Pop3(array('dirname' =>
652 $mail = $cache->get($cache_id);
657 $cache->set($cache_id, $mail);
661 <sect3 id="zend.mail.read-advanced.extending">
662 <title>Extending Protocol Classes</title>
665 Remote storages use two classes:
666 <classname>Zend_Mail_Storage_<Name></classname> and
667 <classname>Zend_Mail_Protocol_<Name></classname>. The protocol class
668 translates the protocol commands and responses from and to <acronym>PHP</acronym>,
669 like methods for the commands or variables with different structures for data.
670 The other/main class implements the common interface.
674 If you need additional protocol features, you can extend the protocol class and use
675 it in the constructor of the main class. As an example, assume we need to knock
676 different ports before we can connect to POP3.
679 <programlisting language="php"><![CDATA[
680 class Example_Mail_Exception extends Zend_Mail_Exception
684 class Example_Mail_Protocol_Exception extends Zend_Mail_Protocol_Exception
688 class Example_Mail_Protocol_Pop3_Knock extends Zend_Mail_Protocol_Pop3
690 private $host, $port;
692 public function __construct($host, $port = null)
694 // no auto connect in this class
699 public function knock($port)
701 $sock = @fsockopen($this->host, $port);
707 public function connect($host = null, $port = null, $ssl = false)
709 if ($host === null) {
712 if ($port === null) {
715 parent::connect($host, $port);
719 class Example_Mail_Pop3_Knock extends Zend_Mail_Storage_Pop3
721 public function __construct(array $params)
723 // ... check $params here! ...
724 $protocol = new Example_Mail_Protocol_Pop3_Knock($params['host']);
726 // do our "special" thing
727 foreach ((array)$params['knock_ports'] as $port) {
728 $protocol->knock($port);
731 // get to correct state
732 $protocol->connect($params['host'], $params['port']);
733 $protocol->login($params['user'], $params['password']);
736 parent::__construct($protocol);
740 $mail = new Example_Mail_Pop3_Knock(array('host' => 'localhost',
742 'password' => 'test',
744 array(1101, 1105, 1111)));
748 As you see, we always assume we're connected, logged in and, if supported, a folder
749 is selected in the constructor of the main class. Thus if you assign your own
750 protocol class, you always need to make sure that's done or the next method will
751 fail if the server doesn't allow it in the current state.
755 <sect3 id="zend.mail.read-advanced.quota">
756 <title>Using Quota (since 1.5)</title>
759 <classname>Zend_Mail_Storage_Writable_Maildir</classname> has support for Maildir++
760 quotas. It's disabled by default, but it's possible to use it manually, if the
761 automatic checks are not desired (this means
762 <methodname>appendMessage()</methodname>, <methodname>removeMessage()</methodname>
763 and <methodname>copyMessage()</methodname> do no checks and do not add entries to
764 the maildirsize file). If enabled, an exception is thrown if you try to write to the
765 maildir and it's already over quota.
769 There are three methods used for quotas: <methodname>getQuota()</methodname>,
770 <methodname>setQuota()</methodname> and <methodname>checkQuota()</methodname>:
773 <programlisting language="php"><![CDATA[
774 $mail = new Zend_Mail_Storage_Writable_Maildir(array('dirname' =>
775 '/home/test/mail/'));
776 $mail->setQuota(true); // true to enable, false to disable
777 echo 'Quota check is now ', $mail->getQuota() ? 'enabled' : 'disabled', "\n";
778 // check quota can be used even if quota checks are disabled
779 echo 'You are ', $mail->checkQuota() ? 'over quota' : 'not over quota', "\n";
783 <methodname>checkQuota()</methodname> can also return a more detailed response:
786 <programlisting language="php"><![CDATA[
787 $quota = $mail->checkQuota(true);
788 echo 'You are ', $quota['over_quota'] ? 'over quota' : 'not over quota', "\n";
792 $quota['quota']['count'],
793 ' messages and use ';
794 echo $quota['size'], ' of ', $quota['quota']['size'], ' octets';
798 If you want to specify your own quota instead of using the one specified in the
799 maildirsize file you can do with <methodname>setQuota()</methodname>:
802 <programlisting language="php"><![CDATA[
803 // message count and octet size supported, order does matter
804 $quota = $mail->setQuota(array('size' => 10000, 'count' => 100));
808 To add your own quota checks use single letters as keys, and they will be preserved
809 (but obviously not checked). It's also possible to extend
810 <classname>Zend_Mail_Storage_Writable_Maildir</classname> to define your own quota
811 only if the maildirsize file is missing (which can happen in Maildir++):
814 <programlisting language="php"><![CDATA[
815 class Example_Mail_Storage_Maildir extends Zend_Mail_Storage_Writable_Maildir {
816 // getQuota is called with $fromStorage = true by quota checks
817 public function getQuota($fromStorage = false) {
819 return parent::getQuota($fromStorage);
820 } catch (Zend_Mail_Storage_Exception $e) {
825 // maildirsize file must be missing
827 list($count, $size) = get_quota_from_somewhere_else();
828 return array('count' => $count, 'size' => $size);