Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.0.0+

How to Download Messages in MessageSet One at a Time

See more IMAP Examples

If a message set contains a huge number of emails, it's NOT a good idea to try to download all at once into an email bundle using a method such as FetchBundle. It's better to iterate over the messages in the set to download one by one.

Chilkat PHP Downloads

Chilkat2 PHP
<?php

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

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

$imap = new Imap();

// Connect using TLS.
$imap->Ssl = true;
$imap->Port = 993;
try {
    $imap->Connect('imap.example.com');

    // Authenticate
    $imap->Login('email_account_login', 'email_account_password');

    // Select an IMAP mailbox
    $imap->SelectMailbox('Inbox');

    // Search for messages and return a set of matching messages.
    // (This example will simply search for ALL messages.)
    $fetchUids = true;

    $messageSet = new MessageSet();
    $imap->QueryMbx('ALL', $fetchUids, $messageSet);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

echo 'Number of messages = ', $messageSet->Count, "\n";

$email = new Email();
$i = 0;
while ($i < $messageSet->Count) {
    try {
        $imap->FetchEmail(false, $messageSet->GetId($i), $fetchUids, $email);
    } catch (\Chilkat2\Exception $e) {
        echo $e->getMessage(), "\n";
        exit;
    }

    echo $email->From, '; ', $email->Subject, "\n";

    $i = $i + 1;
}

echo "OK\n";