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

PowerShell
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"

$success = $false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

$token = New-Object Chilkat.JsonObject
$success = $token.LoadFile("gmail-mail-token.json")
if ($success -ne $true) {
    $("Could not load the protocol token from the private working directory.")
    exit
}

if (($token.JsonTypeOf("access_token") -ne 1) -or ($token.StringOfEquals("access_token","",$true) -eq $true)) {
    $("Authorize or refresh the mailbox first.")
    exit
}

$mailbox = "user@example.com"
$imap = New-Object Chilkat.Imap
$imap.Ssl = $true
$imap.Port = 993
$imap.RequireSslCertVerify = $true
$imap.AuthMethod = "XOAUTH2"
$success = $imap.Connect("imap.gmail.com")
if ($success -ne $true) {
    $("Could not establish the Gmail IMAP TLS connection.")
    exit
}

$success = $imap.Login($mailbox,$token.StringOf("access_token"))
if ($success -ne $true) {
    $imap.Disconnect()
    $("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
    exit
}

$capabilities = $imap.Capability()
if (($imap.LastMethodSuccess -ne $true) -or ($imap.HasCapability("X-GM-EXT-1",$capabilities) -ne $true)) {
    $imap.Logout()
    $imap.Disconnect()
    $("Gmail IMAP extensions are unavailable.")
    exit
}

$folders = New-Object Chilkat.Mailboxes
$success = $imap.MbxList($false,"","*",$folders)
if ($success -ne $true) {
    $imap.Logout()
    $imap.Disconnect()
    $("Could not list Gmail folders.")
    exit
}

$allMail = ""
$folderMatches = 0
$f = 0
while (($f -lt $folders.Count)) {
    if (($folders.HasFlag($f,"\All") -eq $true) -and ($folders.IsSelectable($f) -eq $true)) {
        $allMail = $folders.GetName($f)
        $folderMatches = $folderMatches + 1
    }

    $f = $f + 1
}

if ($folderMatches -ne 1) {
    $imap.Logout()
    $imap.Disconnect()
    $("Expected one selectable folder with the \All special-use attribute. Check label visibility.")
    exit
}

$success = $imap.ExamineMailbox($allMail)
if ($success -ne $true) {
    $imap.Logout()
    $imap.Disconnect()
    $("Could not open All Mail read-only.")
    exit
}

#  This search uses Gmail syntax inside a quoted IMAP search argument.
$query = "has:attachment from:sender@example.net"
$quoted = New-Object Chilkat.StringBuilder
$quoted.Append($query)
if (($quoted.Contains("`r",$true) -eq $true) -or ($quoted.Contains("`n",$true) -eq $true)) {
    $imap.Logout()
    $imap.Disconnect()
    $("A search query must not contain CR or LF.")
    exit
}

$replacements = $quoted.Replace("\","\\")
$replacements = $quoted.Replace("`"","\`"")
$joined1 = New-Object Chilkat.StringBuilder
$joined1.Append("X-GM-RAW `"")
$joined1.Append($quoted.GetAsString())
$joined1.Append("`"")
$criteria = $joined1.GetAsString()
$found = New-Object Chilkat.MessageSet
$success = $imap.QueryMbx($criteria,$true,$found)
if ($success -ne $true) {
    $imap.Logout()
    $imap.Disconnect()
    $("Gmail search failed.")
    exit
}

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