Sample code for 30+ languages & platforms
Objective-C 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 Objective-C Downloads

Objective-C
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoStringTable.h>
#import <CkoBinData.h>

BOOL success = NO;

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

CkoJsonObject *token = [[CkoJsonObject alloc] init];
success = [token LoadFile: @"gmail-token.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not read gmail-token.json from the private working directory.");
    return;
}

if (([[token JsonTypeOf: @"access_token"] intValue] != 1) || ([token StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"An OAuth access token is required.");
    return;
}

CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.AuthToken = [token StringOf: @"access_token"];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
CkoJsonObject *reply = [[CkoJsonObject alloc] init];
NSString *messageId = @"GMAIL_MESSAGE_ID";
NSString *filename = @"attachment.pdf";
CkoStringBuilder *messageUrl = [[CkoStringBuilder alloc] init];
[messageUrl Append: @"https://gmail.googleapis.com/gmail/v1/users/me/messages/"];
[messageUrl Append: [http UrlEncode: messageId]];
CkoStringBuilder *url = [[CkoStringBuilder alloc] init];
[url Append: [messageUrl GetAsString]];
[url Append: @"?format=full"];
success = [http HttpNoBody: @"GET" url: [url GetAsString] response: resp];
if ([resp.StatusCode intValue] == 0) {
    NSLog(@"%@",@"Gmail did not return an HTTP response.");
    return;
}

if ((success != YES) || ([resp.StatusCode intValue] < 200) || ([resp.StatusCode intValue] >= 300)) {
    NSLog(@"%@%d",@"Gmail HTTP ",[resp.StatusCode intValue]);
    success = [reply Load: resp.BodyStr];
    if (success == YES) {
        NSLog(@"%@",[reply StringOf: @"error.message"]);
    }

    return;
}

success = [reply Load: resp.BodyStr];
if (success != YES) {
    NSLog(@"%@",@"Expected a Gmail JSON response.");
    return;
}

CkoStringTable *paths = [[CkoStringTable alloc] init];
success = [paths Append: @"payload"];
if (success != YES) {
    NSLog(@"%@",paths.LastErrorText);
    return;
}

CkoJsonObject *part = [[CkoJsonObject alloc] init];
CkoJsonObject *selected = [[CkoJsonObject alloc] init];
CkoStringBuilder *childPath = [[CkoStringBuilder alloc] init];
int matches = 0;
int p = 0;
while ((p < [paths.Count intValue])) {
    success = [reply ObjectOf2: [paths StringAt: [NSNumber numberWithInt: p]] jsonObj: part];
    if (success != YES) {
        NSLog(@"%@",reply.LastErrorText);
        return;
    }

    if ([part StringOfEquals: @"filename" value: filename caseSensitive: YES] == YES) {
        matches = matches + 1;
        success = [part MakeCopy: selected];
        if (success != YES) {
            NSLog(@"%@",part.LastErrorText);
            return;
        }

        NSLog(@"%@%@",@"Matching MIME part: ",[paths StringAt: [NSNumber numberWithInt: p]]);
    }

    int j = 0;
    while ((j < [[part SizeOfArray: @"parts"] intValue])) {
        [childPath SetString: [paths StringAt: [NSNumber numberWithInt: p]]];
        [childPath Append: @".parts["];
        [childPath AppendInt: [NSNumber numberWithInt: j]];
        [childPath Append: @"]"];
        success = [paths Append: [childPath GetAsString]];
        if (success != YES) {
            NSLog(@"%@",paths.LastErrorText);
            return;
        }

        j = j + 1;
    }

    p = p + 1;
}

if (matches != 1) {
    NSLog(@"%@%d",@"Expected one filename match. Matches: ",matches);
    return;
}

CkoJsonObject *body = [[CkoJsonObject alloc] init];
success = [selected ObjectOf2: @"body" jsonObj: body];
if (success != YES) {
    NSLog(@"%@",selected.LastErrorText);
    return;
}

if ([[body JsonTypeOf: @"size"] intValue] != 2) {
    NSLog(@"%@",@"The selected part has no byte count.");
    return;
}

int expectedSize = [[body IntOf: @"size"] intValue];
if ([[body JsonTypeOf: @"attachmentId"] intValue] == 1) {
    [url SetString: [messageUrl GetAsString]];
    [url Append: @"/attachments/"];
    [url Append: [http UrlEncode: [body StringOf: @"attachmentId"]]];
    success = [http HttpNoBody: @"GET" url: [url GetAsString] response: resp];
    if ([resp.StatusCode intValue] == 0) {
        NSLog(@"%@",@"Gmail did not return an HTTP response.");
        return;
    }

    if ((success != YES) || ([resp.StatusCode intValue] < 200) || ([resp.StatusCode intValue] >= 300)) {
        NSLog(@"%@%d",@"Gmail HTTP ",[resp.StatusCode intValue]);
        success = [reply Load: resp.BodyStr];
        if (success == YES) {
            NSLog(@"%@",[reply StringOf: @"error.message"]);
        }

        return;
    }

    success = [reply Load: resp.BodyStr];
    if (success != YES) {
        NSLog(@"%@",@"Expected a Gmail JSON response.");
        return;
    }

    success = [reply MakeCopy: body];
    if (success != YES) {
        NSLog(@"%@",reply.LastErrorText);
        return;
    }

}

if ([[body JsonTypeOf: @"data"] intValue] != 1) {
    NSLog(@"%@",@"The attachment response has no data.");
    return;
}

CkoBinData *data = [[CkoBinData alloc] init];
if ([body StringOfEquals: @"data" value: @"" caseSensitive: YES] != YES) {
    success = [body BytesOf: @"data" encoding: @"base64url" bd: data];
    if (success != YES) {
        NSLog(@"%@",body.LastErrorText);
        return;
    }

}

if ([data.NumBytes intValue] != expectedSize) {
    NSLog(@"%@",@"Attachment size mismatch.");
    return;
}

success = [data WriteFile: @"downloaded-attachment.bin"];
if (success != YES) {
    NSLog(@"%@",@"Could not save the attachment.");
    return;
}

NSLog(@"%@%d%@",@"Saved ",[data.NumBytes intValue],@" attachment bytes.");