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

Download a Gmail attachment by filename

See more GMail REST API Examples

Start with a Gmail message ID and the exact filename. Walk the root MIME payload and all nested parts. A unique matching part can contain base64url data directly or an attachment ID for a second request. Duplicate filenames are reported so the application can choose a particular MIME part.

The output path is chosen locally. The example saves to downloaded-attachment.bin and verifies the decoded size. Use an appropriate application-chosen filename or extension when adapting it. Gmail’s filename is treated as a matching value.

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 messageId: String? = "GMAIL_MESSAGE_ID"
    var filename: String? = "attachment.pdf"
    let messageUrl = CkoStringBuilder()!
    messageUrl.append(value: "https://gmail.googleapis.com/gmail/v1/users/me/messages/")
    messageUrl.append(value: http.urlEncode(str: messageId))
    let url = CkoStringBuilder()!
    url.append(value: messageUrl.getAsString())
    url.append(value: "?format=full")
    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
    }

    let paths = CkoStringTable()!
    success = paths.append(value: "payload")
    if success != true {
        print("\(paths.lastErrorText!)")
        return
    }

    let part = CkoJsonObject()!
    let selected = CkoJsonObject()!
    let childPath = CkoStringBuilder()!
    var matches: Int = 0
    var p: Int = 0
    while (p < paths.count.intValue) {
        success = reply.objectOf2(jsonPath: paths.string(at: p), jsonObj: part)
        if success != true {
            print("\(reply.lastErrorText!)")
            return
        }

        if part.string(ofEquals: "filename", value: filename, caseSensitive: true) == true {
            matches = matches + 1
            success = part.makeCopy(json: selected)
            if success != true {
                print("\(part.lastErrorText!)")
                return
            }

            print("Matching MIME part: \(paths.string(at: p)!)")
        }

        var j: Int = 0
        while (j < part.size(ofArray: "parts").intValue) {
            childPath.setString(value: paths.string(at: p))
            childPath.append(value: ".parts[")
            childPath.appendInt(value: j)
            childPath.append(value: "]")
            success = paths.append(value: childPath.getAsString())
            if success != true {
                print("\(paths.lastErrorText!)")
                return
            }

            j = j + 1
        }

        p = p + 1
    }

    if matches != 1 {
        print("Expected one filename match. Matches: \(matches)")
        return
    }

    let body = CkoJsonObject()!
    success = selected.objectOf2(jsonPath: "body", jsonObj: body)
    if success != true {
        print("\(selected.lastErrorText!)")
        return
    }

    if body.jsonType(of: "size").intValue != 2 {
        print("The selected part has no byte count.")
        return
    }

    var expectedSize: Int = body.int(of: "size").intValue
    if body.jsonType(of: "attachmentId").intValue == 1 {
        url.setString(value: messageUrl.getAsString())
        url.append(value: "/attachments/")
        url.append(value: http.urlEncode(str: body.string(of: "attachmentId")))
        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
        }

        success = reply.makeCopy(json: body)
        if success != true {
            print("\(reply.lastErrorText!)")
            return
        }

    }

    if body.jsonType(of: "data").intValue != 1 {
        print("The attachment response has no data.")
        return
    }

    let data = CkoBinData()!
    if body.string(ofEquals: "data", value: "", caseSensitive: true) != true {
        success = body.bytes(of: "data", encoding: "base64url", bd: data)
        if success != true {
            print("\(body.lastErrorText!)")
            return
        }

    }

    if data.numBytes.intValue != expectedSize {
        print("Attachment size mismatch.")
        return
    }

    success = data.writeFile(path: "downloaded-attachment.bin")
    if success != true {
        print("Could not save the attachment.")
        return
    }

    print("Saved \(data.numBytes.intValue) attachment bytes.")

}