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

Gmail IMAP: Archive a Message or Move It to Trash

See more GMail SMTP/IMAP/POP Examples

This example changes one message in INBOX. Choose archive to move it to the discovered All Mail folder, or trash to move it to the discovered Trash folder. It resolves a decimal Gmail message ID to a mailbox UID and uses MoveMessages with the server's MOVE capability.

Archiving removes a message from INBOX while retaining it in All Mail. Moving it to Trash is a different action; Gmail normally permanently deletes messages after 30 days there. This example does not empty Trash or permanently delete mail. A message can retain other custom labels when archived.

Folder names are discovered by special-use attributes. Avoid a generic delete/EXPUNGE sequence whose Gmail outcome can depend on account settings and which can affect unrelated messages. If a connection fails during a move, inspect the source and destination before retrying. A concurrent move or deletion can make the UID disappear.

Use the mailbox that authorized the full-mail scope https://mail.google.com/. Obtain the protocol OAuth token and refresh it before running this example. The token is loaded from gmail-mail-token.json in a private working directory; a narrow Gmail REST token is insufficient.

Google documentation

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.

local token = chilkat.JsonObject.new()
local success = token:load_file("gmail-mail-token.json")
if not success then
    print("Could not load the protocol token from the private working directory.")
    return
end

if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
    print("Authorize or refresh the mailbox first.")
    return
end

local mailbox = "user@example.com"
local imap = chilkat.Imap.new()
imap.ssl = true
imap.port = 993
imap.require_ssl_cert_verify = true
imap.auth_method = "XOAUTH2"
success = imap:connect("imap.gmail.com")
if not success then
    print("Could not establish the Gmail IMAP TLS connection.")
    return
end

success = imap:login(mailbox, token:string_of("access_token"))
if not success then
    imap:disconnect()
    print("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
    return
end

local capabilities = imap:capability()
if (not imap.last_method_success) or (not imap:has_capability("X-GM-EXT-1", capabilities)) then
    imap:logout()
    imap:disconnect()
    print("Gmail IMAP extensions are unavailable.")
    return
end

-- Choose archive or trash. This example changes one message's location.
local action = "archive"
if (action ~= "archive") and (action ~= "trash") then
    imap:logout()
    imap:disconnect()
    print("Choose archive or trash.")
    return
end

if not imap:has_capability("MOVE", capabilities) then
    imap:logout()
    imap:disconnect()
    print("The server must support IMAP MOVE.")
    return
end

local folders = chilkat.Mailboxes.new()
success = imap:mbx_list(false, "", "*", folders)
if not success then
    imap:logout()
    imap:disconnect()
    print("Could not list Gmail folders.")
    return
end

local role = "\\All"
if action == "trash" then
    role = "\\Trash"
end

local destination = ""
local count = 0
local i = 0
while i < folders.count do
    if (folders:has_flag(i, role)) and (folders:is_selectable(i)) then
        destination = folders:get_name(i)
        count = count + 1
    end

    i = i + 1
end

if count ~= 1 then
    imap:logout()
    imap:disconnect()
    print("Could not identify the destination folder uniquely.")
    return
end

success = imap:select_mailbox("INBOX")
if not success then
    imap:logout()
    imap:disconnect()
    print("Could not open INBOX for the move.")
    return
end

-- Obtain this decimal string from the Gmail message/thread ID example.
local gmailMessageId = "1278455344230334865"
local idText = chilkat.StringBuilder.new()
idText:append(gmailMessageId)
local validation = chilkat.JsonObject.new()
local matches = idText:regex_match("\\A[1-9][0-9]{0,19}\\z", validation, 1000)
if matches ~= 1 then
    imap:logout()
    imap:disconnect()
    print("Expected a decimal Gmail message ID string.")
    return
end

local target = chilkat.MessageSet.new()
local joined1 = chilkat.StringBuilder.new()
joined1:append("X-GM-MSGID ")
joined1:append(gmailMessageId)
success = imap:query_mbx(joined1:get_as_string(), true, target)
if not success then
    imap:logout()
    imap:disconnect()
    print("Could not find the Gmail message in the selected mailbox.")
    return
end

if target.count ~= 1 then
    imap:logout()
    imap:disconnect()
    print("Expected one message in the selected mailbox. Matches: " .. target.count)
    return
end

local uid = target:to_compact_string()
-- MoveMessages uses UID MOVE and maintains the Imap object's mailbox state.
-- No broad EXPUNGE is issued, and unrelated deleted flags are not committed.
success = imap:move_messages(target, destination)
if not success then
    imap:logout()
    imap:disconnect()
    print("Move failed; verify the mailbox state before retrying after a connection loss.")
    return
end

print("Completed " .. action .. " for Gmail message " .. gmailMessageId)
imap:logout()
imap:disconnect()