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

Gmail IMAP: Read, Add, or Remove Message Labels

See more GMail SMTP/IMAP/POP Examples

Locate a message in INBOX by its decimal Gmail message ID, then read its labels or add/remove one custom label with X-GM-LABELS. The default action is read. Changing action to add or remove modifies the mailbox. Obtain the message ID from the message and thread IDs example.

The code changes only the specified custom label and preserves other labels. A message shown under several labels is still one Gmail message. System labels have different semantics; use the archive/Trash example for those operations. If the message left INBOX, select its current mailbox before searching.

This focused raw-command example accepts printable ASCII custom labels beginning with a letter or digit, escapes quotes and backslashes, and displays the returned label list in IMAP syntax. Non-ASCII names require IMAP modified UTF-7 encoding. The response is not parsed by splitting on spaces because quoted names can contain spaces.

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 statusText = chilkat.StringBuilder.new()
local statusMatch = chilkat.JsonObject.new()
local completed = 0
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

success = imap:select_mailbox("INBOX")
if not success then
    imap:logout()
    imap:disconnect()
    print("Could not open INBOX.")
    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()
-- Choose read, add, or remove. Only add/remove changes the message.
local action = "read"
local label = "Example label"
if (action ~= "read") and ((action ~= "add") and (action ~= "remove")) then
    imap:logout()
    imap:disconnect()
    print("Choose read, add, or remove.")
    return
end

local labelText = chilkat.StringBuilder.new()
labelText:append(label)
-- This raw-command example accepts printable ASCII custom labels only.
-- For non-ASCII labels, encode modified UTF-7 before quoting the command argument.
matches = labelText:regex_match("\\A[A-Za-z0-9][\\x20-\\x7e]*\\z", validation, 1000)
if matches ~= 1 then
    imap:logout()
    imap:disconnect()
    print("Use a printable ASCII custom label starting with a letter or digit.")
    return
end

local replacements = labelText:replace("\\", "\\\\")
replacements = labelText:replace("\"", "\\\"")
local response = ""
local command = ""
if action ~= "read" then
    local operation = "+X-GM-LABELS.SILENT"
    if action == "remove" then
        operation = "-X-GM-LABELS.SILENT"
    end

    local joined2 = chilkat.StringBuilder.new()
    joined2:append("UID STORE ")
    joined2:append(uid)
    joined2:append(" ")
    joined2:append(operation)
    joined2:append(" (\"")
    joined2:append(labelText:get_as_string())
    joined2:append("\")")
    command = joined2:get_as_string()
    response = imap:send_raw_command(command)
    statusText:set_string(response)
    -- A completed raw exchange can still return NO or BAD. Require tagged OK.
    completed = statusText:regex_match("(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z", statusMatch, 1000)

    if (not imap.last_method_success) or (completed ~= 1) then
        imap:logout()
        imap:disconnect()
        print("Label update failed. Check the custom label and mailbox permissions.")
        return
    end
end

local joined3 = chilkat.StringBuilder.new()
joined3:append("UID FETCH ")
joined3:append(uid)
joined3:append(" (X-GM-LABELS)")
response = imap:send_raw_command(joined3:get_as_string())
statusText:set_string(response)
-- A completed raw exchange can still return NO or BAD. Require tagged OK.
completed = statusText:regex_match("(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z", statusMatch, 1000)

if (not imap.last_method_success) or (completed ~= 1) then
    imap:logout()
    imap:disconnect()
    print("Could not read the message labels.")
    return
end

-- Display the server's label-list syntax, including quoted/encoded names.
-- This is a FETCH response, not an authentication/session log.
print(response)
imap:logout()
imap:disconnect()