Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.0.0+

Delete All IMAP Email

Demonstrates two ways to delete all email in a mailbox on an IMAP server.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

local imap = chilkat.Imap.new()

-- Turn on session logging:
imap.keep_session_log = true

-- Connect to an IMAP server.
-- Use TLS
imap.ssl = true
imap.port = 993
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.RubyMail")
if not success then
    print(imap.last_error_text)
    return
end

-- Get the complete set of Uids for email in the selected mailbox.
local messageSet = chilkat.MessageSet.new()
success = imap:query_mbx("ALL", true, messageSet)
if not success then
    print(imap.last_error_text)
    return
end

-- Set the Deleted flag for each message.
-- (ExpungeAndClose must be called to finalize the delete.)
success = imap:set_flags(messageSet, "Deleted", 1)
if not success then
    print(imap.last_error_text)
    return
end

-- Alternatively, the Deleted flag may be set for each UID
-- individiually, but this is less efficient:
local i = 0
local n = messageSet.count
while i < n do
    success = imap:set_flag(messageSet:get_id(i), messageSet.has_uids, "Deleted", 1)
    if not success then
        print(imap.last_error_text)
        return
    end

    i = i + 1
end

-- Expunge and close the mailbox.
success = imap:expunge_and_close()
if not success then
    print(imap.last_error_text)
    return
end

-- Display the session log.
print(imap.session_log)

-- Disconnect from the IMAP server.
success = imap:disconnect()