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

Reply to a message in its existing Gmail thread

See more GMail REST API Examples

Live send. Supply the Gmail ID of a received message and use an authorized From address. Fetch its raw MIME so Chilkat.Email can parse encoded headers and recipient addresses. Send a plain-text reply to Reply-To, falling back to From. The reply goes to the original sender or reply address.

The request supplies Gmail’s threadId and matching Subject. The MIME In-Reply-To contains the original RFC Message-ID. References preserves the conversation ancestry and appends that Message-ID. Select a message with a valid Message-ID and review its recipient before running this sending example. Authorize both gmail.readonly and gmail.send, or use gmail.modify as shown below.

Authorize the application with https://www.googleapis.com/auth/gmail.modify. 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()!
    let url = CkoStringBuilder()!
    url.append(value: "https://gmail.googleapis.com/gmail/v1/users/me/messages/")
    url.append(value: "GMAIL_MESSAGE_ID")
    url.append(value: "?format=raw")
    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
    }

    if (reply.jsonType(of: "threadId").intValue != 1) || (reply.string(ofEquals: "threadId", value: "", caseSensitive: true) == true) {
        print("Expected threadId in the response.")
        return
    }

    if (reply.jsonType(of: "raw").intValue != 1) || (reply.string(ofEquals: "raw", value: "", caseSensitive: true) == true) {
        print("Expected raw in the response.")
        return
    }

    var threadId: String? = reply.string(of: "threadId")
    let originalMime = CkoBinData()!
    success = reply.bytes(of: "raw", encoding: "base64url", bd: originalMime)
    if success != true {
        print("\(reply.lastErrorText!)")
        return
    }

    let original = CkoEmail()!
    success = original.set(fromMimeBd: originalMime)
    if success != true {
        print("\(original.lastErrorText!)")
        return
    }

    var messageIdHeader: String? = original.getHeaderField(fieldName: "Message-ID")
    if (original.lastMethodSuccess != true) || (messageIdHeader == "") {
        print("The original message needs a Message-ID for this threaded reply.")
        return
    }

    let email = CkoEmail()!
    email.from = "Sender <sender@example.com>"
    //  Use the parsed Reply-To mailbox list when present, otherwise use From.
    var replyAddress: String? = original.replyTo
    if replyAddress == "" {
        replyAddress = original.from
    }

    success = email.addMultiple(to: replyAddress)
    if success != true {
        print("\(email.lastErrorText!)")
        return
    }

    if email.numTo.intValue == 0 {
        print("The original message has no usable reply address.")
        return
    }

    email.subject = original.subject
    email.charset = "utf-8"
    email.body = "Thank you for your message."
    email.addHeaderField(fieldName: "In-Reply-To", fieldValue: messageIdHeader)
    let references = CkoStringBuilder()!
    var previousReferences: String? = original.getHeaderField(fieldName: "References")
    if (original.lastMethodSuccess == true) && (previousReferences != "") {
        references.append(value: previousReferences)
        references.append(value: " ")
    }

    references.append(value: messageIdHeader)
    email.addHeaderField(fieldName: "References", fieldValue: references.getAsString())
    let mime = CkoBinData()!
    success = email.getMimeBd(bindat: mime)
    if success != true {
        print("\(email.lastErrorText!)")
        return
    }

    let request = CkoJsonObject()!
    success = request.updateBd(jsonPath: "raw", encoding: "base64url", bd: mime)
    if success != true {
        print("\(request.lastErrorText!)")
        return
    }

    success = request.updateString(jsonPath: "threadId", value: threadId)
    if success != true {
        print("\(request.lastErrorText!)")
        return
    }

    success = http.httpJson(verb: "POST", url: "https://gmail.googleapis.com/gmail/v1/users/me/messages/send", json: request, contentType: "application/json", 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
    }

    if (reply.jsonType(of: "id").intValue != 1) || (reply.string(ofEquals: "id", value: "", caseSensitive: true) == true) {
        print("Expected id in the response.")
        return
    }

    print("Sent reply ID: \(reply.string(of: "id")!)")
    print("Thread ID: \(reply.string(of: "threadId")!)")

}