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 Ruby Downloads
require 'chilkat'
success = false
# Assumes Chilkat is unlocked. See Global Unlock Sample.
token = Chilkat::CkJsonObject.new()
success = token.LoadFile("gmail-mail-token.json")
if (success != true)
print "Could not read gmail-mail-token.json from the private working directory." + "\n";
exit
end
if ((token.JsonTypeOf("access_token") != 1) or (token.StringOfEquals("access_token","",true) == true))
print "An OAuth access token is required. Authorize or refresh the account first." + "\n";
exit
end
mailbox = "user@example.com"
imap = Chilkat::CkImap.new()
imap.put_Ssl(true)
imap.put_Port(993)
imap.put_RequireSslCertVerify(true)
imap.put_AuthMethod("XOAUTH2")
success = imap.Connect("imap.gmail.com")
if (success != true)
print "Could not establish the Gmail IMAP TLS connection." + "\n";
exit
end
success = imap.Login(mailbox,token.stringOf("access_token"))
if (success != true)
imap.Disconnect()
print "IMAP authentication failed. Check the mailbox, token scope, expiry, and Workspace policy." + "\n";
exit
end
success = imap.ExamineMailbox("INBOX")
if (success != true)
imap.Logout()
imap.Disconnect()
print "Could not examine INBOX." + "\n";
exit
end
# Capture only the EXAMINE response, after authentication has completed.
print imap.lastResponse() + "\n";
# Sample flags without marking messages read. Sequence numbers are session-local.
if (imap.get_NumMessages() > 0)
sequence = 1
flags = imap.fetchFlags(sequence,false)
if (imap.get_LastMethodSuccess() != true)
imap.Logout()
imap.Disconnect()
print "Could not fetch flags; the message may have changed or disappeared." + "\n";
exit
end
print "Sequence " + sequence.to_s() + ": " + flags + "\n";
end
folders = Chilkat::CkMailboxes.new()
success = imap.MbxList(false,"","*",folders)
if (success != true)
imap.Logout()
imap.Disconnect()
print "Could not list folders." + "\n";
exit
end
i = 0
while (i < folders.get_Count())
if (folders.HasFlag(i,"\\Junk") == true)
print "Spam folder: " + folders.getName(i) + "\n";
end
i = i + 1
end
imap.Logout()
imap.Disconnect()