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

Swift

func chilkatTest() {
    var success: Bool = false

    var replacements: Int
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    let token = CkoJsonObject()!
    success = token.loadFile(path: "gmail-mail-token.json")
    if success != true {
        print("Could not load the protocol token from the private working directory.")
        return
    }

    if (token.jsonType(of: "access_token").intValue != 1) || (token.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
        print("Authorize or refresh the mailbox first.")
        return
    }

    var mailbox: String? = "user@example.com"
    let imap = CkoImap()!
    imap.ssl = true
    imap.port = 993
    imap.requireSslCertVerify = true
    imap.authMethod = "XOAUTH2"
    success = imap.connect(hostname: "imap.gmail.com")
    if success != true {
        print("Could not establish the Gmail IMAP TLS connection.")
        return
    }

    success = imap.login(login: mailbox, password: token.string(of: "access_token"))
    if success != true {
        imap.disconnect()
        print("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
        return
    }

    var capabilities: String? = imap.capability()
    if (imap.lastMethodSuccess != true) || (imap.hasCapability(name: "X-GM-EXT-1", capabilityResponse: capabilities) != true) {
        imap.logout()
        imap.disconnect()
        print("Gmail IMAP extensions are unavailable.")
        return
    }

    let folders = CkoMailboxes()!
    success = imap.mbxList(subscribed: false, reference: "", mbxPattern: "*", mboxes: folders)
    if success != true {
        imap.logout()
        imap.disconnect()
        print("Could not list Gmail folders.")
        return
    }

    var allMail: String? = ""
    var folderMatches: Int = 0
    var f: Int = 0
    while (f < folders.count.intValue) {
        if (folders.hasFlag(index: f, flagName: "\\All") == true) && (folders.isSelectable(index: f) == true) {
            allMail = folders.getName(index: f)
            folderMatches = folderMatches + 1
        }

        f = f + 1
    }

    if folderMatches != 1 {
        imap.logout()
        imap.disconnect()
        print("Expected one selectable folder with the \\All special-use attribute. Check label visibility.")
        return
    }

    success = imap.examineMailbox(mailbox: allMail)
    if success != true {
        imap.logout()
        imap.disconnect()
        print("Could not open All Mail read-only.")
        return
    }

    //  This search uses Gmail syntax inside a quoted IMAP search argument.
    var query: String? = "has:attachment from:sender@example.net"
    let quoted = CkoStringBuilder()!
    quoted.append(value: query)
    if (quoted.contains(str: "\r", caseSensitive: true) == true) || (quoted.contains(str: "\n", caseSensitive: true) == true) {
        imap.logout()
        imap.disconnect()
        print("A search query must not contain CR or LF.")
        return
    }

    replacements = quoted.replace(value: "\\", replacement: "\\\\").intValue
    replacements = quoted.replace(value: "\"", replacement: "\\\"").intValue
    let joined1 = CkoStringBuilder()!
    joined1.append(value: "X-GM-RAW \"")
    joined1.append(value: quoted.getAsString())
    joined1.append(value: "\"")
    var criteria: String? = joined1.getAsString()
    let found = CkoMessageSet()!
    success = imap.queryMbx(criteria: criteria, bUid: true, msgSet: found)
    if success != true {
        imap.logout()
        imap.disconnect()
        print("Gmail search failed.")
        return
    }

    //  Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
    print("Matching messages: \(found.count.intValue)")
    print("UID set: \(found.toCompactString()!)")
    imap.logout()
    imap.disconnect()

}