6.0.0-git
2024-04-19
Last Modified 2012-01-03 by Guest

Using the Horde/Imap_Client Library

These are some basic examples. All examples assume you have a fully configured IMP, and can get the client object from the IMP API:

$imap = $registry->mail->imapOb();

Basics

Get a list of all messages in the INBOX:

$query = new Horde_Imap_Client_Fetch_Query();
$mbox = new Horde_Imap_Client_Mailbox('INBOX');

// $list is a Horde_Imap_Client_Data_Fetch object.
$list = $imap->fetch($mbox, $query);

Get a list of messages in INBOX, since a certain date:

$query = new Horde_Imap_Client_Search_Query();
$query->dateSearch(
    new Horde_Date($date_string),
    Horde_Imap_Client_Search_Query::DATE_SINCE
);
$mbox = new Horde_Imap_Client_Mailbox('INBOX');

// $list is a Horde_Imap_Client_Data_Search object.
$results = $imap->search($mbox, $query);

// The list of message uids.
var_dump($results['match']);

Using the above message ids, fetch the plaintext body of the first email:

$mbox = new Horde_Imap_Client_Mailbox('INBOX');
$query = new Horde_Imap_Client_Fetch_Query();
$query->structure();

$list = $imap->fetch($mbox, $query, array('ids' => $results['match']));
$message = array_pop($list);
$uid = $message->getUid();
$part = $message->getStructure();
$id = $part->findBody();
$body = $part->getPart($id);

$query2 = new Horde_Imap_Client_Fetch_Query();
$query2->bodyPart($id, array(
    'peek' => true,
    'decode' => true
));
$results = $imap->fetch($mbox, $query2, array('ids' => new Horde_Imap_Client_Ids(array($uid))));
$message2 = array_pop($results);
$text = $message2->getBodyPart($id);
if (!$message2->getBodyPartDecode($id)) {
    // Quick way to transfer decode contents
    $body->setContents($message2->getBodyPart($id));
    $text = $body->getContents();
}

echo $text;