Sample code for 30+ languages & platforms
PowerBuilder

IMAP Delete Old Email (before a specified date)

See more IMAP Examples

Demonstrates how to delete email older than a particular date.

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Imap
integer li_FetchUids
oleobject loo_MessageSet
oleobject loo_Email
integer i
integer li_Count
integer li_HeaderOnly

li_Success = 0

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

loo_Imap = create oleobject
li_rc = loo_Imap.ConnectToNewObject("Chilkat.Imap")
if li_rc < 0 then
    destroy loo_Imap
    MessageBox("Error","Connecting to COM object failed")
    return
end if

// Connect to an IMAP server.
// Use TLS
loo_Imap.Ssl = 1
loo_Imap.Port = 993
// Use your IMAP server domain.  This example 
li_Success = loo_Imap.Connect("imap.example.com")
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

// Login
li_Success = loo_Imap.Login("myLogin","myPassword")
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

// Select an IMAP mailbox
li_Success = loo_Imap.SelectMailbox("Inbox")
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

// Get message ID's for emails older than 1/1/2025
li_FetchUids = 1
loo_MessageSet = create oleobject
li_rc = loo_MessageSet.ConnectToNewObject("Chilkat.MessageSet")

li_Success = loo_Imap.QueryMbx("SENTBEFORE 01-Jan-2025",li_FetchUids,loo_MessageSet)
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    destroy loo_MessageSet
    return
end if

// If desired, we can examine the Subject of each email to be deleted..
loo_Email = create oleobject
li_rc = loo_Email.ConnectToNewObject("Chilkat.Email")

i = 0
li_Count = loo_MessageSet.Count
li_HeaderOnly = 1

do while i < li_Count
    li_Success = loo_Imap.FetchEmail(li_HeaderOnly,loo_MessageSet.GetId(i),1,loo_Email)
    if li_Success = 0 then
        Write-Debug loo_Imap.LastErrorText
        destroy loo_Imap
        destroy loo_MessageSet
        destroy loo_Email
        return
    end if

    Write-Debug loo_Email.LocalDateStr
    Write-Debug loo_Email.Subject

    i = i + 1
loop

// Set the Deleted flag for each message:
li_Success = loo_Imap.SetFlags(loo_MessageSet,"Deleted",1)
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    destroy loo_MessageSet
    destroy loo_Email
    return
end if

// Expunge and close the mailbox.
li_Success = loo_Imap.ExpungeAndClose()
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    destroy loo_MessageSet
    destroy loo_Email
    return
end if

// Disconnect from the IMAP server.
li_Success = loo_Imap.Disconnect()


destroy loo_Imap
destroy loo_MessageSet
destroy loo_Email