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

Subscribe to Mailboxes and List Subscribed Mailboxes

See more IMAP Examples

Demonstrates how to list subscribed mailboxes, and unsubscribe/subscribe to a mailbox.

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\Imap;
use Chilkat2\Mailboxes;

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

$imap = new Imap();

// Connect to an IMAP server.
// Use TLS
$imap->Ssl = true;
$imap->Port = 993;
try {
    $imap->Connect('imap.example.com');

    // Login
    $imap->Login('myLogin', 'myPassword');

    // First examine the already subscribed mailboxes.
    $refName = '';
    $wildcardedMailbox = '*';
    $subscribed = true;

    $mboxes = new Mailboxes();
    $imap->MbxList($subscribed, $refName, $wildcardedMailbox, $mboxes);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

$i = 0;
while ($i < $mboxes->Count) {
    echo $mboxes->GetName($i), "\n";
    $i = $i + 1;
}

echo "----\n";

// Sample output.

// INBOX
// INBOX/recent
// INBOX/misc
// INBOX/misc/solutions
// ...
// Outbox
// Deleted Items
// Sent Items
// Drafts
// Junk E-mail
// Trash
// Sent
// Templates

// Let's unsubscribe to "INBOX/misc/solutions".
try {
    $imap->Unsubscribe('INBOX/misc/solutions');

    // Get the list of subscribed mailboxes again to verify that "INBOX/misc/solutions" is missing.
    $imap->MbxList($subscribed, '', 'INBOX/misc*', $mboxes);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

$i = 0;
while ($i < $mboxes->Count) {
    echo $mboxes->GetName($i), "\n";
    $i = $i + 1;
}

echo "----\n";

// Re-subscribe to "INBOX/misc/solutions".
try {
    $imap->Subscribe('INBOX/misc/solutions');

    // Get the list of subscribed mailboxes again to verify that "INBOX/misc/solutions" is back in the list.
    $imap->MbxList($subscribed, '', 'INBOX/misc*', $mboxes);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

$i = 0;
while ($i < $mboxes->Count) {
    echo $mboxes->GetName($i), "\n";
    $i = $i + 1;
}

echo "----\n";

// Disconnect from the IMAP server.
$imap->Disconnect();