Gmail IMAP: Inspect Flags and Locate the Spam Folder
See more IMAP Examples
Inspect the current INBOX flags and discover Gmail's Spam folder through its \Junk special-use attribute. The example reads the first message's flags, if present, and makes no mailbox changes.
Client-specific Junk/NonJunk keywords are not a portable spam verdict. A mailbox's \Junk LIST attribute identifies a special folder; it is not a message flag. Use current server responses rather than a historical transcript. For Gmail label membership, see X-GM-LABELS.
First authorize the mailbox for https://mail.google.com/ and refresh the token as needed. Read the current token from gmail-mail-token.json in a private working directory. Narrow Gmail REST scopes do not authorize these protocols. Keep the token and authentication logs private.
See the Gmail SMTP, IMAP, and POP3 guide for current authentication choices and Gmail-specific examples.
Chilkat Lua Downloads
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 read gmail-mail-token.json 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("An OAuth access token is required. Authorize or refresh the account 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, token scope, expiry, and Workspace policy.")
return
end
success = imap:examine_mailbox("INBOX")
if not success then
imap:logout()
imap:disconnect()
print("Could not examine INBOX.")
return
end
-- Capture only the EXAMINE response, after authentication has completed.
print(imap.last_response)
-- Sample flags without marking messages read. Sequence numbers are session-local.
if imap.num_messages > 0 then
local sequence = 1
local flags = imap:fetch_flags(sequence, false)
if not imap.last_method_success then
imap:logout()
imap:disconnect()
print("Could not fetch flags; the message may have changed or disappeared.")
return
end
print("Sequence " .. sequence .. ": " .. flags)
end
local folders = chilkat.Mailboxes.new()
success = imap:mbx_list(false, "", "*", folders)
if not success then
imap:logout()
imap:disconnect()
print("Could not list folders.")
return
end
local i = 0
while i < folders.count do
if folders:has_flag(i, "\\Junk") then
print("Spam folder: " .. folders:get_name(i))
end
i = i + 1
end
imap:logout()
imap:disconnect()