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

Delete All IMAP Email

Demonstrates two ways to delete all email in a mailbox on an IMAP server.

Chilkat PHP Downloads

PHP
<?php

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();

// Turn on session logging:
$imap->KeepSessionLog = true;

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

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

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

    // Get the complete set of Uids for email in the selected mailbox.
    $messageSet = new MessageSet();
    $imap->QueryMbx('ALL', true, $messageSet);

    // Set the Deleted flag for each message.
    // (ExpungeAndClose must be called to finalize the delete.)
    $imap->SetFlags($messageSet, 'Deleted', 1);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Alternatively, the Deleted flag may be set for each UID
// individiually, but this is less efficient:
$i = 0;
$n = $messageSet->Count;
while ($i < $n) {
    try {
        $imap->SetFlag($messageSet->GetId($i), $messageSet->HasUids, 'Deleted', 1);
    } catch (\Chilkat2\Exception $e) {
        echo $e->getMessage(), "\n";
        exit;
    }

    $i = $i + 1;
}

// Expunge and close the mailbox.
try {
    $imap->ExpungeAndClose();
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Display the session log.
echo $imap->SessionLog, "\n";

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