Sample code for 30+ languages & platforms
Xbase++ 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 Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oImap
LOCAL nFetchUids
LOCAL oMessageSet
LOCAL oEmail
LOCAL i
LOCAL nCount
LOCAL nHeaderOnly

nSuccess := 0

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

oImap := CreateObject("Chilkat.Imap")

//  Connect to an IMAP server.
//  Use TLS
oImap:Ssl := 1
oImap:Port := 993
//  Use your IMAP server domain.  This example 
nSuccess := oImap:Connect("imap.example.com")
IF (nSuccess == 0)
    ? oImap:LastErrorText
    oImap:destroy()
    RETURN
ENDIF

//  Login
nSuccess := oImap:Login("myLogin", "myPassword")
IF (nSuccess == 0)
    ? oImap:LastErrorText
    oImap:destroy()
    RETURN
ENDIF

//  Select an IMAP mailbox
nSuccess := oImap:SelectMailbox("Inbox")
IF (nSuccess == 0)
    ? oImap:LastErrorText
    oImap:destroy()
    RETURN
ENDIF

//  Get message ID's for emails older than 1/1/2025
nFetchUids := 1
oMessageSet := CreateObject("Chilkat.MessageSet")
nSuccess := oImap:QueryMbx("SENTBEFORE 01-Jan-2025", nFetchUids, oMessageSet)
IF (nSuccess == 0)
    ? oImap:LastErrorText
    oImap:destroy()
    oMessageSet:destroy()
    RETURN
ENDIF

//  If desired, we can examine the Subject of each email to be deleted..
oEmail := CreateObject("Chilkat.Email")
i := 0
nCount := oMessageSet:Count
nHeaderOnly := 1

DO WHILE i < nCount
    nSuccess := oImap:FetchEmail(nHeaderOnly, oMessageSet:GetId(i), 1, oEmail)
    IF (nSuccess == 0)
        ? oImap:LastErrorText
        oImap:destroy()
        oMessageSet:destroy()
        oEmail:destroy()
        RETURN
    ENDIF

    ? oEmail:LocalDateStr
    ? oEmail:Subject

    i := i + 1
ENDDO

//  Set the Deleted flag for each message:
nSuccess := oImap:SetFlags(oMessageSet, "Deleted", 1)
IF (nSuccess == 0)
    ? oImap:LastErrorText
    oImap:destroy()
    oMessageSet:destroy()
    oEmail:destroy()
    RETURN
ENDIF

//  Expunge and close the mailbox.
nSuccess := oImap:ExpungeAndClose()
IF (nSuccess == 0)
    ? oImap:LastErrorText
    oImap:destroy()
    oMessageSet:destroy()
    oEmail:destroy()
    RETURN
ENDIF

//  Disconnect from the IMAP server.
nSuccess := oImap:Disconnect()

oImap:destroy()
oMessageSet:destroy()
oEmail:destroy()