Sample code for 30+ languages & platforms
Tcl 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 Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

set token [new_CkJsonObject]

set success [CkJsonObject_LoadFile $token "gmail-mail-token.json"]
if {$success != 1} then {
    puts "Could not load the protocol token from the private working directory."
    delete_CkJsonObject $token
    exit
}

if {expr [[CkJsonObject_JsonTypeOf $token "access_token"] != 1]  ||  [[CkJsonObject_StringOfEquals $token "access_token" "" 1] == 1]} then {
    puts "Authorize or refresh the mailbox first."
    delete_CkJsonObject $token
    exit
}

set mailbox "user@example.com"
set imap [new_CkImap]

CkImap_put_Ssl $imap 1
CkImap_put_Port $imap 993
CkImap_put_RequireSslCertVerify $imap 1
CkImap_put_AuthMethod $imap "XOAUTH2"
set success [CkImap_Connect $imap "imap.gmail.com"]
if {$success != 1} then {
    puts "Could not establish the Gmail IMAP TLS connection."
    delete_CkJsonObject $token
    delete_CkImap $imap
    exit
}

set success [CkImap_Login $imap $mailbox [CkJsonObject_stringOf $token "access_token"]]
if {$success != 1} then {
    CkImap_Disconnect $imap
    puts "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy."
    delete_CkJsonObject $token
    delete_CkImap $imap
    exit
}

set capabilities [CkImap_capability $imap]
if {expr [[CkImap_get_LastMethodSuccess $imap] != 1]  ||  [[CkImap_HasCapability $imap "X-GM-EXT-1" $capabilities] != 1]} then {
    CkImap_Logout $imap
    CkImap_Disconnect $imap
    puts "Gmail IMAP extensions are unavailable."
    delete_CkJsonObject $token
    delete_CkImap $imap
    exit
}

set folders [new_CkMailboxes]

set success [CkImap_MbxList $imap 0 "" "*" $folders]
if {$success != 1} then {
    CkImap_Logout $imap
    CkImap_Disconnect $imap
    puts "Could not list Gmail folders."
    delete_CkJsonObject $token
    delete_CkImap $imap
    delete_CkMailboxes $folders
    exit
}

set allMail ""
set folderMatches 0
set f 0
while {$f < [CkMailboxes_get_Count $folders]} {
    if {expr [[CkMailboxes_HasFlag $folders $f "\\All"] == 1]  &&  [[CkMailboxes_IsSelectable $folders $f] == 1]} then {
        set allMail [CkMailboxes_getName $folders $f]
        set folderMatches [expr $folderMatches + 1]
    }

    set f [expr $f + 1]
}
if {$folderMatches != 1} then {
    CkImap_Logout $imap
    CkImap_Disconnect $imap
    puts "Expected one selectable folder with the \\All special-use attribute. Check label visibility."
    delete_CkJsonObject $token
    delete_CkImap $imap
    delete_CkMailboxes $folders
    exit
}

set success [CkImap_ExamineMailbox $imap $allMail]
if {$success != 1} then {
    CkImap_Logout $imap
    CkImap_Disconnect $imap
    puts "Could not open All Mail read-only."
    delete_CkJsonObject $token
    delete_CkImap $imap
    delete_CkMailboxes $folders
    exit
}

#  This search uses Gmail syntax inside a quoted IMAP search argument.
set query "has:attachment from:sender@example.net"
set quoted [new_CkStringBuilder]

CkStringBuilder_Append $quoted $query
if {expr [[CkStringBuilder_Contains $quoted "\r" 1] == 1]  ||  [[CkStringBuilder_Contains $quoted "\n" 1] == 1]} then {
    CkImap_Logout $imap
    CkImap_Disconnect $imap
    puts "A search query must not contain CR or LF."
    delete_CkJsonObject $token
    delete_CkImap $imap
    delete_CkMailboxes $folders
    delete_CkStringBuilder $quoted
    exit
}

set replacements [CkStringBuilder_Replace $quoted "\\" "\\\\"]
set replacements [CkStringBuilder_Replace $quoted "\"" "\\\""]
set joined1 [new_CkStringBuilder]

CkStringBuilder_Append $joined1 "X-GM-RAW \""
CkStringBuilder_Append $joined1 [CkStringBuilder_getAsString $quoted]
CkStringBuilder_Append $joined1 "\""
set criteria [CkStringBuilder_getAsString $joined1]
set found [new_CkMessageSet]

set success [CkImap_QueryMbx $imap $criteria 1 $found]
if {$success != 1} then {
    CkImap_Logout $imap
    CkImap_Disconnect $imap
    puts "Gmail search failed."
    delete_CkJsonObject $token
    delete_CkImap $imap
    delete_CkMailboxes $folders
    delete_CkStringBuilder $quoted
    delete_CkStringBuilder $joined1
    delete_CkMessageSet $found
    exit
}

#  Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
puts "Matching messages: [CkMessageSet_get_Count $found]"
puts "UID set: [CkMessageSet_toCompactString $found]"
CkImap_Logout $imap
CkImap_Disconnect $imap

delete_CkJsonObject $token
delete_CkImap $imap
delete_CkMailboxes $folders
delete_CkStringBuilder $quoted
delete_CkStringBuilder $joined1
delete_CkMessageSet $found