Sample code for 30+ languages & platforms
Objective-C

IMAP Delete Old Email (before a specified date)

See more IMAP Examples

Demonstrates how to delete email older than a particular date.

Chilkat Objective-C Downloads

Objective-C
#import <CkoImap.h>
#import <CkoMessageSet.h>
#import <CkoEmail.h>

BOOL success = NO;

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

CkoImap *imap = [[CkoImap alloc] init];

// Connect to an IMAP server.
// Use TLS
imap.Ssl = YES;
imap.Port = [NSNumber numberWithInt:993];
// Use your IMAP server domain.  This example 
success = [imap Connect: @"imap.example.com"];
if (success == NO) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

// Login
success = [imap Login: @"myLogin" password: @"myPassword"];
if (success == NO) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

// Select an IMAP mailbox
success = [imap SelectMailbox: @"Inbox"];
if (success == NO) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

// Get message ID's for emails older than 1/1/2025
BOOL fetchUids = YES;
CkoMessageSet *messageSet = [[CkoMessageSet alloc] init];
success = [imap QueryMbx: @"SENTBEFORE 01-Jan-2025" bUid: fetchUids msgSet: messageSet];
if (success == NO) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

// If desired, we can examine the Subject of each email to be deleted..
CkoEmail *email = [[CkoEmail alloc] init];
int i = 0;
int count = [messageSet.Count intValue];
BOOL headerOnly = YES;

while (i < count) {
    success = [imap FetchEmail: headerOnly msgId: [messageSet GetId: [NSNumber numberWithInt: i]] bUid: YES email: email];
    if (success == NO) {
        NSLog(@"%@",imap.LastErrorText);
        return;
    }

    NSLog(@"%@",email.LocalDateStr);
    NSLog(@"%@",email.Subject);

    i = i + 1;
}

// Set the Deleted flag for each message:
success = [imap SetFlags: messageSet flagName: @"Deleted" value: [NSNumber numberWithInt: 1]];
if (success == NO) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

// Expunge and close the mailbox.
success = [imap ExpungeAndClose];
if (success == NO) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

// Disconnect from the IMAP server.
success = [imap Disconnect];