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

Gmail IMAP: Search with Gmail Search Syntax

See more GMail SMTP/IMAP/POP Examples

Search with Gmail operators through X-GM-RAW, using QueryMbx to obtain UIDs. The example discovers All Mail and opens it read-only. It quotes the query for the IMAP command rather than URL-encoding it.

IMAP search is limited to the selected mailbox. All Mail normally covers inbox and archived messages, but excludes Spam and Trash; a Gmail search operator cannot expand an IMAP search beyond its selected mailbox. An empty result is successful. Returned IMAP UIDs are mailbox-specific and are not Gmail message IDs. Persist them only with their mailbox and UIDVALIDITY.

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 CkPython Downloads

CkPython
import sys
import chilkat

success = False

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

token = chilkat.CkJsonObject()
success = token.LoadFile("gmail-mail-token.json")
if (success != True):
    print("Could not load the protocol token from the private working directory.")
    sys.exit()

if ((token.JsonTypeOf("access_token") != 1) or (token.StringOfEquals("access_token","",True) == True)):
    print("Authorize or refresh the mailbox first.")
    sys.exit()

mailbox = "user@example.com"
imap = chilkat.CkImap()
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.")
    sys.exit()

success = imap.Login(mailbox,token.stringOf("access_token"))
if (success != True):
    imap.Disconnect()
    print("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
    sys.exit()

capabilities = imap.capability()
if ((imap.get_LastMethodSuccess() != True) or (imap.HasCapability("X-GM-EXT-1",capabilities) != True)):
    imap.Logout()
    imap.Disconnect()
    print("Gmail IMAP extensions are unavailable.")
    sys.exit()

folders = chilkat.CkMailboxes()
success = imap.MbxList(False,"","*",folders)
if (success != True):
    imap.Logout()
    imap.Disconnect()
    print("Could not list Gmail folders.")
    sys.exit()

allMail = ""
folderMatches = 0
f = 0
while (f < folders.get_Count()) :
    if ((folders.HasFlag(f,"\\All") == True) and (folders.IsSelectable(f) == True)):
        allMail = folders.getName(f)
        folderMatches = folderMatches + 1

    f = f + 1

if (folderMatches != 1):
    imap.Logout()
    imap.Disconnect()
    print("Expected one selectable folder with the \\All special-use attribute. Check label visibility.")
    sys.exit()

success = imap.ExamineMailbox(allMail)
if (success != True):
    imap.Logout()
    imap.Disconnect()
    print("Could not open All Mail read-only.")
    sys.exit()

#  This search uses Gmail syntax inside a quoted IMAP search argument.
query = "has:attachment from:sender@example.net"
quoted = chilkat.CkStringBuilder()
quoted.Append(query)
if ((quoted.Contains("\r",True) == True) or (quoted.Contains("\n",True) == True)):
    imap.Logout()
    imap.Disconnect()
    print("A search query must not contain CR or LF.")
    sys.exit()

replacements = quoted.Replace("\\","\\\\")
replacements = quoted.Replace("\"","\\\"")
joined1 = chilkat.CkStringBuilder()
joined1.Append("X-GM-RAW \"")
joined1.Append(quoted.getAsString())
joined1.Append("\"")
criteria = joined1.getAsString()
found = chilkat.CkMessageSet()
success = imap.QueryMbx(criteria,True,found)
if (success != True):
    imap.Logout()
    imap.Disconnect()
    print("Gmail search failed.")
    sys.exit()

#  Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
print("Matching messages: " + str(found.get_Count()))
print("UID set: " + found.toCompactString())
imap.Logout()
imap.Disconnect()