Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.0.0+

Search Gmail by sender, subject, date, or attachment

See more GMail REST API Examples

Choose a Gmail search query, follow every result page, and fetch From and Subject headers for each match. Edit the query to use operators such as from:, subject:, after:, before:, has:attachment, and filename:. Quoted phrases and special characters are URL-encoded once.

Gmail search dates use midnight Pacific Standard Time. Use Unix timestamps in seconds for exact date boundaries in another timezone. Spam and Trash are excluded unless includeSpamTrash=true is added. Search requires gmail.readonly or a broader mail scope. Query searches are unavailable with gmail.metadata.

Authorize the application with https://www.googleapis.com/auth/gmail.readonly. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

Google documentation

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

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

    if (token.jsonType(of: "access_token").intValue != 1) || (token.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
        print("An OAuth access token is required.")
        return
    }

    let http = CkoHttp()!
    http.requireSslCertVerify = true
    http.authToken = token.string(of: "access_token")
    let resp = CkoHttpResponse()!
    let reply = CkoJsonObject()!
    var searchQuery: String? = "from:sender@example.com has:attachment filename:pdf"
    let baseUrl = CkoStringBuilder()!
    baseUrl.append(value: "https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=100&q=")
    baseUrl.append(value: http.urlEncode(str: searchQuery))
    let url = CkoStringBuilder()!
    var pageToken: String? = ""
    let page = CkoJsonObject()!
    var total: Int = 0
    var more: Bool = true
    while (more == true) {
        url.setString(value: baseUrl.getAsString())
        url.append(value: "&pageToken=")
        url.append(value: http.urlEncode(str: pageToken))
        success = http.httpNoBody(verb: "GET", url: url.getAsString(), response: resp)
        if resp.statusCode.intValue == 0 {
            print("Gmail did not return an HTTP response.")
            return
        }

        if (success != true) || (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
            print("Gmail HTTP \(resp.statusCode.intValue)")
            success = reply.load(json: resp.bodyStr)
            if success == true {
                print("\(reply.string(of: "error.message")!)")
            }

            return
        }

        success = reply.load(json: resp.bodyStr)
        if success != true {
            print("Expected a Gmail JSON response.")
            return
        }

        //  Keep this page while individual message requests reuse reply.
        success = reply.makeCopy(json: page)
        if success != true {
            print("\(reply.lastErrorText!)")
            return
        }

        var i: Int = 0
        while (i < page.size(ofArray: "messages").intValue) {
            page.i = i
            var messageId: String? = page.string(of: "messages[i].id")
            url.setString(value: "https://gmail.googleapis.com/gmail/v1/users/me/messages/")
            url.append(value: http.urlEncode(str: messageId))
            url.append(value: "?format=metadata&metadataHeaders=From&metadataHeaders=Subject")
            success = http.httpNoBody(verb: "GET", url: url.getAsString(), response: resp)
            //  A message can disappear between the search and the metadata request.
            if resp.statusCode.intValue != 404 {
                if resp.statusCode.intValue == 0 {
                    print("Gmail did not return an HTTP response.")
                    return
                }

                if (success != true) || (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
                    print("Gmail HTTP \(resp.statusCode.intValue)")
                    success = reply.load(json: resp.bodyStr)
                    if success == true {
                        print("\(reply.string(of: "error.message")!)")
                    }

                    return
                }

                success = reply.load(json: resp.bodyStr)
                if success != true {
                    print("Expected a Gmail JSON response.")
                    return
                }

                print("Message: \(messageId!)")
                var h: Int = 0
                while (h < reply.size(ofArray: "payload.headers").intValue) {
                    reply.i = h
                    print("\(reply.string(of: "payload.headers[i].name")!): \(reply.string(of: "payload.headers[i].value")!)")
                    h = h + 1
                }

                total = total + 1
            }

            i = i + 1
        }

        pageToken = ""
        if page.jsonType(of: "nextPageToken").intValue == 1 {
            pageToken = page.string(of: "nextPageToken")
        }

        more = pageToken != ""
    }

    print("Matching messages read: \(total)")

}