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

VB.NET
Dim success As Boolean = False

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

Dim token As New Chilkat.JsonObject
success = token.LoadFile("gmail-mail-token.json")
If (success <> True) Then
    Debug.WriteLine("Could not load the protocol token from the private working directory.")
    Exit Sub
End If

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

Dim mailbox As String = "user@example.com"
Dim imap As New Chilkat.Imap
imap.Ssl = True
imap.Port = 993
imap.RequireSslCertVerify = True
imap.AuthMethod = "XOAUTH2"
success = imap.Connect("imap.gmail.com")
If (success <> True) Then
    Debug.WriteLine("Could not establish the Gmail IMAP TLS connection.")
    Exit Sub
End If

success = imap.Login(mailbox,token.StringOf("access_token"))
If (success <> True) Then
    imap.Disconnect()
    Debug.WriteLine("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
    Exit Sub
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()
    Debug.WriteLine("Gmail IMAP extensions are unavailable.")
    Exit Sub
End If

Dim folders As New Chilkat.Mailboxes
success = imap.MbxList(False,"","*",folders)
If (success <> True) Then
    imap.Logout()
    imap.Disconnect()
    Debug.WriteLine("Could not list Gmail folders.")
    Exit Sub
End If

Dim allMail As String = ""
Dim folderMatches As Integer = 0
Dim f As Integer = 0
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
End While
If (folderMatches <> 1) Then
    imap.Logout()
    imap.Disconnect()
    Debug.WriteLine("Expected one selectable folder with the \All special-use attribute. Check label visibility.")
    Exit Sub
End If

success = imap.ExamineMailbox(allMail)
If (success <> True) Then
    imap.Logout()
    imap.Disconnect()
    Debug.WriteLine("Could not open All Mail read-only.")
    Exit Sub
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 New Chilkat.StringBuilder
quoted.Append(query)
If ((quoted.Contains(vbCr,True) = True) Or (quoted.Contains(vbLf,True) = True)) Then
    imap.Logout()
    imap.Disconnect()
    Debug.WriteLine("A search query must not contain CR or LF.")
    Exit Sub
End If

replacements = quoted.Replace("\","\\")
replacements = quoted.Replace("""","\""")
Dim joined1 As New Chilkat.StringBuilder
joined1.Append("X-GM-RAW """)
joined1.Append(quoted.GetAsString())
joined1.Append("""")
Dim criteria As String = joined1.GetAsString()
Dim found As New Chilkat.MessageSet
success = imap.QueryMbx(criteria,True,found)
If (success <> True) Then
    imap.Logout()
    imap.Disconnect()
    Debug.WriteLine("Gmail search failed.")
    Exit Sub
End If

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