Sample code for 30+ languages & platforms
PHP

Fetch a MessageSet into an EmailBundle

See more IMAP Examples

Demonstrates the Chilkat Imap.FetchMsgSet method, which downloads the messages identified by a MessageSet and appends them to an EmailBundle. The arguments are headersOnly, the MessageSet, and the EmailBundle (which is not cleared). This example searches for unseen messages and downloads the whole set.

Background: This is the natural pairing with QueryMbx: search to get a MessageSet of matching identifiers, then download exactly those messages in one call. Fetching a set is far more efficient than looping one message at a time, and it returns an EmailBundle you iterate with MessageCount and EmailAt. Pass headersOnly = true to pull just headers for a fast preview list.

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\Email;
use Chilkat2\EmailBundle;
use Chilkat2\Imap;
use Chilkat2\MessageSet;

// Demonstrates the Imap.FetchMsgSet method, which downloads the messages identified by a
// MessageSet and appends them to an EmailBundle.  The 1st argument is headersOnly, the 2nd
// is the MessageSet, and the 3rd is the EmailBundle (which is not cleared).

$imap = new Imap();

$imap->Ssl = true;
$imap->Port = 993;

try {
    $imap->Connect('imap.example.com');

    $imap->Login('user@example.com', 'myPassword');

    $imap->SelectMailbox('Inbox');

    // Find the messages to download (here, the unseen messages by UID).
    $msgSet = new MessageSet();
    $imap->QueryMbx('UNSEEN', true, $msgSet);

    // Download the messages in the set (full bodies) into a bundle.
    $bundle = new EmailBundle();
    $imap->FetchMsgSet(false, $msgSet, $bundle);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

$n = $bundle->MessageCount;
echo 'Fetched ', $n, " messages.\n";
$email = new Email();
for ($i = 0; $i < $n; $i++) {
    $bundle->EmailAt($i, $email);
    echo $email->Subject, "\n";
}

try {
    $imap->Disconnect();
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}