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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Integer iReplacements
    Handle hoToken
    String sMailbox
    Handle hoImap
    String sCapabilities
    Variant vFolders
    Handle hoFolders
    String sAllMail
    Integer iFolderMatches
    Integer f
    String sQuery
    Handle hoQuoted
    Handle hoJoined1
    String sCriteria
    Variant vFound
    Handle hoFound
    String sTemp1
    Integer iTemp1
    Boolean bTemp1
    Boolean bTemp2

    Move False To iSuccess

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    Get Create (RefClass(cComChilkatJsonObject)) To hoToken
    If (Not(IsComObjectCreated(hoToken))) Begin
        Send CreateComObject of hoToken
    End
    Get ComLoadFile Of hoToken "gmail-mail-token.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not load the protocol token from the private working directory."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoToken "access_token" To iTemp1
    Get ComStringOfEquals Of hoToken "access_token" "" True To bTemp1
    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
        Showln "Authorize or refresh the mailbox first."
        Procedure_Return
    End

    Move "user@example.com" To sMailbox
    Get Create (RefClass(cComChilkatImap)) To hoImap
    If (Not(IsComObjectCreated(hoImap))) Begin
        Send CreateComObject of hoImap
    End
    Set ComSsl Of hoImap To True
    Set ComPort Of hoImap To 993
    Set ComRequireSslCertVerify Of hoImap To True
    Set ComAuthMethod Of hoImap To "XOAUTH2"
    Get ComConnect Of hoImap "imap.gmail.com" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not establish the Gmail IMAP TLS connection."
        Procedure_Return
    End

    Get ComStringOf Of hoToken "access_token" To sTemp1
    Get ComLogin Of hoImap sMailbox sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Get ComDisconnect Of hoImap To iSuccess
        Showln "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy."
        Procedure_Return
    End

    Get ComCapability Of hoImap To sCapabilities
    Get ComLastMethodSuccess Of hoImap To bTemp1
    Get ComHasCapability Of hoImap "X-GM-EXT-1" sCapabilities To bTemp2
    If ((bTemp1 <> True) Or (bTemp2 <> True)) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Gmail IMAP extensions are unavailable."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatMailboxes)) To hoFolders
    If (Not(IsComObjectCreated(hoFolders))) Begin
        Send CreateComObject of hoFolders
    End
    Get pvComObject of hoFolders to vFolders
    Get ComMbxList Of hoImap False "" "*" vFolders To iSuccess
    If (iSuccess <> True) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Could not list Gmail folders."
        Procedure_Return
    End

    Move "" To sAllMail
    Move 0 To iFolderMatches
    Move 0 To f
    While (f < (ComCount(hoFolders)))
        Get ComHasFlag Of hoFolders f "\All" To bTemp1
        Get ComIsSelectable Of hoFolders f To bTemp2
        If ((bTemp1 = True) And (bTemp2 = True)) Begin
            Get ComGetName Of hoFolders f To sAllMail
            Move (iFolderMatches + 1) To iFolderMatches
        End

        Move (f + 1) To f
    Loop

    If (iFolderMatches <> 1) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Expected one selectable folder with the \All special-use attribute. Check label visibility."
        Procedure_Return
    End

    Get ComExamineMailbox Of hoImap sAllMail To iSuccess
    If (iSuccess <> True) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Could not open All Mail read-only."
        Procedure_Return
    End

    //  This search uses Gmail syntax inside a quoted IMAP search argument.
    Move "has:attachment from:sender@example.net" To sQuery
    Get Create (RefClass(cComChilkatStringBuilder)) To hoQuoted
    If (Not(IsComObjectCreated(hoQuoted))) Begin
        Send CreateComObject of hoQuoted
    End
    Get ComAppend Of hoQuoted sQuery To iSuccess
    Get ComContains Of hoQuoted (character(13)) True To bTemp1
    Get ComContains Of hoQuoted (character(10)) True To bTemp2
    If ((bTemp1 = True) Or (bTemp2 = True)) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "A search query must not contain CR or LF."
        Procedure_Return
    End

    Get ComReplace Of hoQuoted "\" "\\" To iReplacements
    Get ComReplace Of hoQuoted '"' '\"' To iReplacements
    Get Create (RefClass(cComChilkatStringBuilder)) To hoJoined1
    If (Not(IsComObjectCreated(hoJoined1))) Begin
        Send CreateComObject of hoJoined1
    End
    Get ComAppend Of hoJoined1 'X-GM-RAW "' To iSuccess
    Get ComGetAsString Of hoQuoted To sTemp1
    Get ComAppend Of hoJoined1 sTemp1 To iSuccess
    Get ComAppend Of hoJoined1 '"' To iSuccess
    Get ComGetAsString Of hoJoined1 To sCriteria
    Get Create (RefClass(cComChilkatMessageSet)) To hoFound
    If (Not(IsComObjectCreated(hoFound))) Begin
        Send CreateComObject of hoFound
    End
    Get pvComObject of hoFound to vFound
    Get ComQueryMbx Of hoImap sCriteria True vFound To iSuccess
    If (iSuccess <> True) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Gmail search failed."
        Procedure_Return
    End

    //  Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
    Get ComCount Of hoFound To iTemp1
    Showln "Matching messages: " iTemp1
    Get ComToCompactString Of hoFound To sTemp1
    Showln "UID set: " sTemp1
    Get ComLogout Of hoImap To iSuccess
    Get ComDisconnect Of hoImap To iSuccess


End_Procedure