Lua Requires Chilkat v11.0.0+
Lua
IMAP Delete Old Email (before a specified date)
See more IMAP Examples
Demonstrates how to delete email older than a particular date.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- This example assumes the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
local imap = chilkat.Imap.new()
-- Connect to an IMAP server.
-- Use TLS
imap.ssl = true
imap.port = 993
-- Use your IMAP server domain. This example
local success = imap:connect("imap.example.com")
if not success then
print(imap.last_error_text)
return
end
-- Login
success = imap:login("myLogin", "myPassword")
if not success then
print(imap.last_error_text)
return
end
-- Select an IMAP mailbox
success = imap:select_mailbox("Inbox")
if not success then
print(imap.last_error_text)
return
end
-- Get message ID's for emails older than 1/1/2025
local fetchUids = true
local messageSet = chilkat.MessageSet.new()
success = imap:query_mbx("SENTBEFORE 01-Jan-2025", fetchUids, messageSet)
if not success then
print(imap.last_error_text)
return
end
-- If desired, we can examine the Subject of each email to be deleted..
local email = chilkat.Email.new()
local i = 0
local count = messageSet.count
local headerOnly = true
while i < count do
success = imap:fetch_email(headerOnly, messageSet:get_id(i), true, email)
if not success then
print(imap.last_error_text)
return
end
print(email.local_date_str)
print(email.subject)
i = i + 1
end
-- Set the Deleted flag for each message:
success = imap:set_flags(messageSet, "Deleted", 1)
if not success then
print(imap.last_error_text)
return
end
-- Expunge and close the mailbox.
success = imap:expunge_and_close()
if not success then
print(imap.last_error_text)
return
end
-- Disconnect from the IMAP server.
success = imap:disconnect()