Swift GMail: Search for Messages with Subject Containing a Word

Back to Index

Return messages matching the specified query. See https://support.google.com/mail/answer/7190?hl=en for additional information about search operators. This example searches for all emails having the whole word "ADVChina" in the subject.

Documentation: https://support.google.com/mail/answer/7190?hl=en

CURL Command

curl -X GET https://www.googleapis.com/gmail/v1/users/me/messages?q=subject:ADVChina \
    --header "Authorization: Bearer GMAIL_TOKEN"

Swift Example


func chilkatTest() {
    let rest = CkoRest()
    var success: Bool

    //  URL: https://www.googleapis.com/gmail/v1/users/me/messages?q=subject:ADVChina
    var bTls: Bool = true
    var port: Int = 443
    var bAutoReconnect: Bool = true
    success = rest.Connect("www.googleapis.com", port: port, tls: bTls, autoReconnect: bAutoReconnect)
    if success != true {
        print("ConnectFailReason: \(rest.ConnectFailReason.intValue)")
        print("\(rest.LastErrorText)")
        return
    }

    rest.AddHeader("Authorization", value: "Bearer GMAIL_TOKEN")

    let sbResponseBody = CkoStringBuilder()
    success = rest.FullRequestNoBodySb("GET", uriPath: "/gmail/v1/users/me/messages?q=subject:ADVChina", sb: sbResponseBody)
    if success != true {
        print("\(rest.LastErrorText)")
        return
    }

    var respStatusCode: Int = rest.ResponseStatusCode.intValue
    if respStatusCode >= 400 {
        print("Response Status Code = \(respStatusCode)")
        print("Response Header:")
        print("\(rest.ResponseHeader)")
        print("Response Body:")
        print("\(sbResponseBody.GetAsString())")
        return
    }

    let jsonResponse = CkoJsonObject()
    jsonResponse.LoadSb(sbResponseBody)

    //  See the Online Tool for Generating JSON Parse Code
    var i: Int
    var count_i: Int

    var resultSizeEstimate: Int = jsonResponse.IntOf("resultSizeEstimate").intValue
    i = 0
    count_i = jsonResponse.SizeOfArray("messages").intValue
    while i < count_i {
        jsonResponse.I = i
        var id: String? = jsonResponse.StringOf("messages[i].id")
        var threadId: String? = jsonResponse.StringOf("messages[i].threadId")
        i = i + 1
    }


}

Sample JSON Response Body

{
  "messages": [
    {
      "id": "166e50fed0b9b0cb",
      "threadId": "166e50fed0b9b0cb"
    },
    {
      "id": "166c12e5fee013fe",
      "threadId": "166c12e5fee013fe"
    },
    {
      "id": "1669cc9a926bb8c1",
      "threadId": "1669cc9a926bb8c1"
    },
    {
      "id": "16678c485e7f0a0c",
      "threadId": "16678c485e7f0a0c"
    }
  ],
  "resultSizeEstimate": 4
}