Sample code for 30+ languages & platforms
Classic ASP

IMAP Delete Old Email (before a specified date)

See more IMAP Examples

Demonstrates how to delete email older than a particular date.

Chilkat Classic ASP Downloads

Classic ASP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<%
success = 0

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

set imap = Server.CreateObject("Chilkat.Imap")

' Connect to an IMAP server.
' Use TLS
imap.Ssl = 1
imap.Port = 993
' Use your IMAP server domain.  This example 
success = imap.Connect("imap.example.com")
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( imap.LastErrorText) & "</pre>"
    Response.End
End If

' Login
success = imap.Login("myLogin","myPassword")
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( imap.LastErrorText) & "</pre>"
    Response.End
End If

' Select an IMAP mailbox
success = imap.SelectMailbox("Inbox")
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( imap.LastErrorText) & "</pre>"
    Response.End
End If

' Get message ID's for emails older than 1/1/2025
fetchUids = 1
set messageSet = Server.CreateObject("Chilkat.MessageSet")
success = imap.QueryMbx("SENTBEFORE 01-Jan-2025",fetchUids,messageSet)
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( imap.LastErrorText) & "</pre>"
    Response.End
End If

' If desired, we can examine the Subject of each email to be deleted..
set email = Server.CreateObject("Chilkat.Email")
i = 0
count = messageSet.Count
headerOnly = 1

Do While i < count
    success = imap.FetchEmail(headerOnly,messageSet.GetId(i),1,email)
    If (success = 0) Then
        Response.Write "<pre>" & Server.HTMLEncode( imap.LastErrorText) & "</pre>"
        Response.End
    End If

    Response.Write "<pre>" & Server.HTMLEncode( email.LocalDateStr) & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( email.Subject) & "</pre>"

    i = i + 1
Loop

' Set the Deleted flag for each message:
success = imap.SetFlags(messageSet,"Deleted",1)
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( imap.LastErrorText) & "</pre>"
    Response.End
End If

' Expunge and close the mailbox.
success = imap.ExpungeAndClose()
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( imap.LastErrorText) & "</pre>"
    Response.End
End If

' Disconnect from the IMAP server.
success = imap.Disconnect()

%>
</body>
</html>