Sample code for 30+ languages & platforms
Tcl

IMAP Delete Old Email (before a specified date)

See more IMAP Examples

Demonstrates how to delete email older than a particular date.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

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

set imap [new_CkImap]

# Connect to an IMAP server.
# Use TLS
CkImap_put_Ssl $imap 1
CkImap_put_Port $imap 993
# Use your IMAP server domain.  This example 
set success [CkImap_Connect $imap "imap.example.com"]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imap]
    delete_CkImap $imap
    exit
}

# Login
set success [CkImap_Login $imap "myLogin" "myPassword"]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imap]
    delete_CkImap $imap
    exit
}

# Select an IMAP mailbox
set success [CkImap_SelectMailbox $imap "Inbox"]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imap]
    delete_CkImap $imap
    exit
}

# Get message ID's for emails older than 1/1/2025
set fetchUids 1
set messageSet [new_CkMessageSet]

set success [CkImap_QueryMbx $imap "SENTBEFORE 01-Jan-2025" $fetchUids $messageSet]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imap]
    delete_CkImap $imap
    delete_CkMessageSet $messageSet
    exit
}

# If desired, we can examine the Subject of each email to be deleted..
set email [new_CkEmail]

set i 0
set count [CkMessageSet_get_Count $messageSet]
set headerOnly 1

while {$i < $count} {
    set success [CkImap_FetchEmail $imap $headerOnly [CkMessageSet_GetId $messageSet $i] 1 $email]
    if {$success == 0} then {
        puts [CkImap_lastErrorText $imap]
        delete_CkImap $imap
        delete_CkMessageSet $messageSet
        delete_CkEmail $email
        exit
    }

    puts [CkEmail_localDateStr $email]
    puts [CkEmail_subject $email]

    set i [expr $i + 1]
}

# Set the Deleted flag for each message:
set success [CkImap_SetFlags $imap $messageSet "Deleted" 1]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imap]
    delete_CkImap $imap
    delete_CkMessageSet $messageSet
    delete_CkEmail $email
    exit
}

# Expunge and close the mailbox.
set success [CkImap_ExpungeAndClose $imap]
if {$success == 0} then {
    puts [CkImap_lastErrorText $imap]
    delete_CkImap $imap
    delete_CkMessageSet $messageSet
    delete_CkEmail $email
    exit
}

# Disconnect from the IMAP server.
set success [CkImap_Disconnect $imap]

delete_CkImap $imap
delete_CkMessageSet $messageSet
delete_CkEmail $email