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

IMAP Delete Old Email (before a specified date)

See more IMAP Examples

Demonstrates how to delete email older than a particular date.

Chilkat PHP Downloads

PHP
<?php

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

// 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;
// Use your IMAP server domain.  This example
try {
    $imap->Connect('imap.example.com');

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

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

    // Get message ID's for emails older than 1/1/2025
    $fetchUids = true;
    $messageSet = new MessageSet();
    $imap->QueryMbx('SENTBEFORE 01-Jan-2025', $fetchUids, $messageSet);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// If desired, we can examine the Subject of each email to be deleted..
$email = new Email();
$i = 0;
$count = $messageSet->Count;
$headerOnly = true;

while ($i < $count) {
    try {
        $imap->FetchEmail($headerOnly, $messageSet->GetId($i), true, $email);
    } catch (\Chilkat2\Exception $e) {
        echo $e->getMessage(), "\n";
        exit;
    }

    echo $email->LocalDateStr, "\n";
    echo $email->Subject, "\n";

    $i = $i + 1;
}

// Set the Deleted flag for each message:
try {
    $imap->SetFlags($messageSet, 'Deleted', 1);

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

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