Swift GMail: Get a specific message (format="minimal")

Back to Index

Gets a specific message using format=minimal.

Documentation: https://developers.google.com/gmail/api/v1/reference/users/messages/get



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

    //   Provide a previously obtained OAuth2 access token.
    let oauth2 = CkoOAuth2()
    oauth2.AccessToken = "OAUTH2_ACCESS_TOKEN"
    rest.SetAuthOAuth2(oauth2)

    success = rest.Connect("www.googleapis.com", port: 443, tls: true, autoReconnect: true)
    if success != true {
        print("\(rest.LastErrorText)")
        return
    }

    rest.AddPathParam("messageId", value: "15fc237e79da4174")

    rest.AddQueryParam("format", value: "minimal")

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

    if rest.ResponseStatusCode.integerValue != 200 {
        print("Received error response code: \(rest.ResponseStatusCode.integerValue)")
        print("Response body:")
        print("\(sbJson.GetAsString())")
        return
    }

    let json = CkoJsonObject()
    json.LoadSb(sbJson)

    //  The following code parses the JSON response.
    //  A sample JSON response is shown below the sample code.
    var id: String?
    var threadId: String?
    var snippet: String?
    var historyId: String?
    var internalDate: String?
    var sizeEstimate: Int
    var i: Int
    var count_i: Int
    var strVal: String?

    id = json.StringOf("id")
    threadId = json.StringOf("threadId")
    snippet = json.StringOf("snippet")
    historyId = json.StringOf("historyId")
    internalDate = json.StringOf("internalDate")
    sizeEstimate = json.IntOf("sizeEstimate").integerValue
    i = 0
    count_i = json.SizeOfArray("labelIds").integerValue
    while i < count_i {
        json.I = i
        strVal = json.StringOf("labelIds[i]")
        i = i + 1
    }

    print("Example Completed.")

}

Sample JSON Response Body

{
  "id": "15fc237e79da4174",
  "threadId": "15fc237e79da4174",
  "labelIds": [
    "IMPORTANT",
    "SENT",
    "INBOX"
  ],
  "snippet": "This is a test email with 2 attachments.",
  "historyId": "1582",
  "internalDate": "1510791964000",
  "sizeEstimate": 11153
}