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

B4X
Dim success As Boolean = False

Dim replacements As Int
'  Assumes Chilkat is unlocked. See Global Unlock Sample.

Dim token As ChilkatJsonObject
token.Initialize
success = token.LoadFile("gmail-mail-token.json")
If success <> True Then
    Log("Could not load the protocol token from the private working directory.")
    Return
End If

If (token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token", "", True) = True) Then
    Log("Authorize or refresh the mailbox first.")
    Return
End If

Dim mailbox As String = "user@example.com"
Dim imap As ChilkatImap
imap.Initialize("imap")
imap.Ssl = True
imap.Port = 993
imap.RequireSslCertVerify = True
imap.AuthMethod = "XOAUTH2"
success = imap.Connect("imap.gmail.com")
If success <> True Then
    Log("Could not establish the Gmail IMAP TLS connection.")
    Return
End If

success = imap.Login(mailbox, token.StringOf("access_token"))
If success <> True Then
    imap.Disconnect
    Log("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
    Return
End If

Dim capabilities As String = imap.Capability
If (imap.LastMethodSuccess <> True) Or (imap.HasCapability("X-GM-EXT-1", capabilities) <> True) Then
    imap.Logout
    imap.Disconnect
    Log("Gmail IMAP extensions are unavailable.")
    Return
End If

Dim folders As ChilkatMailboxes
folders.Initialize
success = imap.MbxList(False, "", "*", folders)
If success <> True Then
    imap.Logout
    imap.Disconnect
    Log("Could not list Gmail folders.")
    Return
End If

Dim allMail As String = ""
Dim folderMatches As Int = 0
Dim f As Int = 0
Do While (f < folders.Count)
    If (folders.HasFlag(f, "\All") = True) And (folders.IsSelectable(f) = True) Then
        allMail = folders.GetName(f)
        folderMatches = folderMatches + 1
    End If

    f = f + 1
Loop
If folderMatches <> 1 Then
    imap.Logout
    imap.Disconnect
    Log("Expected one selectable folder with the \All special-use attribute. Check label visibility.")
    Return
End If

success = imap.ExamineMailbox(allMail)
If success <> True Then
    imap.Logout
    imap.Disconnect
    Log("Could not open All Mail read-only.")
    Return
End If

'  This search uses Gmail syntax inside a quoted IMAP search argument.
Dim query As String = "has:attachment from:sender@example.net"
Dim quoted As ChilkatStringBuilder
quoted.Initialize
quoted.Append(query)
If (quoted.Contains(Chr(13), True) = True) Or (quoted.Contains(Chr(10), True) = True) Then
    imap.Logout
    imap.Disconnect
    Log("A search query must not contain CR or LF.")
    Return
End If

replacements = quoted.Replace("\", "\\")
replacements = quoted.Replace(Chr(34), "\" & Chr(34))
Dim joined1 As ChilkatStringBuilder
joined1.Initialize
joined1.Append("X-GM-RAW " & Chr(34))
joined1.Append(quoted.GetAsString)
joined1.Append(Chr(34))
Dim criteria As String = joined1.GetAsString
Dim found As ChilkatMessageSet
found.Initialize
success = imap.QueryMbx(criteria, True, found)
If success <> True Then
    imap.Logout
    imap.Disconnect
    Log("Gmail search failed.")
    Return
End If

'  Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
Log("Matching messages: " & found.Count)
Log("UID set: " & found.ToCompactString)
imap.Logout
imap.Disconnect