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

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

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

    CkJsonObject token = new CkJsonObject();
    success = token.LoadFile("gmail-token.json");
    if (success != true) {
        Log.i(TAG, "Could not read gmail-token.json from the private working directory.");
        return;
        }

    if ((token.JsonTypeOf("access_token") != 1) or (token.StringOfEquals("access_token","",true) == true)) {
        Log.i(TAG, "An OAuth access token is required.");
        return;
        }

    CkHttp http = new CkHttp();
    http.put_RequireSslCertVerify(true);
    http.put_AuthToken(token.stringOf("access_token"));
    CkHttpResponse resp = new CkHttpResponse();
    CkJsonObject reply = new CkJsonObject();
    String messageId = "GMAIL_MESSAGE_ID";
    String filename = "attachment.pdf";
    CkStringBuilder messageUrl = new CkStringBuilder();
    messageUrl.Append("https://gmail.googleapis.com/gmail/v1/users/me/messages/");
    messageUrl.Append(http.urlEncode(messageId));
    CkStringBuilder url = new CkStringBuilder();
    url.Append(messageUrl.getAsString());
    url.Append("?format=full");
    success = http.HttpNoBody("GET",url.getAsString(),resp);
    if (resp.get_StatusCode() == 0) {
        Log.i(TAG, "Gmail did not return an HTTP response.");
        return;
        }

    if ((success != true) or (resp.get_StatusCode() < 200) or (resp.get_StatusCode() >= 300)) {
        Log.i(TAG, "Gmail HTTP " + String.valueOf(resp.get_StatusCode()));
        success = reply.Load(resp.bodyStr());
        if (success == true) {
            Log.i(TAG, reply.stringOf("error.message"));
            }

        return;
        }

    success = reply.Load(resp.bodyStr());
    if (success != true) {
        Log.i(TAG, "Expected a Gmail JSON response.");
        return;
        }

    CkStringTable paths = new CkStringTable();
    success = paths.Append("payload");
    if (success != true) {
        Log.i(TAG, paths.lastErrorText());
        return;
        }

    CkJsonObject part = new CkJsonObject();
    CkJsonObject selected = new CkJsonObject();
    CkStringBuilder childPath = new CkStringBuilder();
    int matches = 0;
    int p = 0;
    while ((p < paths.get_Count())) {
        success = reply.ObjectOf2(paths.stringAt(p),part);
        if (success != true) {
            Log.i(TAG, reply.lastErrorText());
            return;
            }

        if (part.StringOfEquals("filename",filename,true) == true) {
            matches = matches + 1;
            success = part.MakeCopy(selected);
            if (success != true) {
                Log.i(TAG, part.lastErrorText());
                return;
                }

            Log.i(TAG, "Matching MIME part: " + paths.stringAt(p));
            }

        int j = 0;
        while ((j < part.SizeOfArray("parts"))) {
            childPath.SetString(paths.stringAt(p));
            childPath.Append(".parts[");
            childPath.AppendInt(j);
            childPath.Append("]");
            success = paths.Append(childPath.getAsString());
            if (success != true) {
                Log.i(TAG, paths.lastErrorText());
                return;
                }

            j = j + 1;
            }

        p = p + 1;
        }

    if (matches != 1) {
        Log.i(TAG, "Expected one filename match. Matches: " + String.valueOf(matches));
        return;
        }

    CkJsonObject body = new CkJsonObject();
    success = selected.ObjectOf2("body",body);
    if (success != true) {
        Log.i(TAG, selected.lastErrorText());
        return;
        }

    if (body.JsonTypeOf("size") != 2) {
        Log.i(TAG, "The selected part has no byte count.");
        return;
        }

    int expectedSize = body.IntOf("size");
    if (body.JsonTypeOf("attachmentId") == 1) {
        url.SetString(messageUrl.getAsString());
        url.Append("/attachments/");
        url.Append(http.urlEncode(body.stringOf("attachmentId")));
        success = http.HttpNoBody("GET",url.getAsString(),resp);
        if (resp.get_StatusCode() == 0) {
            Log.i(TAG, "Gmail did not return an HTTP response.");
            return;
            }

        if ((success != true) or (resp.get_StatusCode() < 200) or (resp.get_StatusCode() >= 300)) {
            Log.i(TAG, "Gmail HTTP " + String.valueOf(resp.get_StatusCode()));
            success = reply.Load(resp.bodyStr());
            if (success == true) {
                Log.i(TAG, reply.stringOf("error.message"));
                }

            return;
            }

        success = reply.Load(resp.bodyStr());
        if (success != true) {
            Log.i(TAG, "Expected a Gmail JSON response.");
            return;
            }

        success = reply.MakeCopy(body);
        if (success != true) {
            Log.i(TAG, reply.lastErrorText());
            return;
            }

        }

    if (body.JsonTypeOf("data") != 1) {
        Log.i(TAG, "The attachment response has no data.");
        return;
        }

    CkBinData data = new CkBinData();
    if (body.StringOfEquals("data","",true) != true) {
        success = body.BytesOf("data","base64url",data);
        if (success != true) {
            Log.i(TAG, body.lastErrorText());
            return;
            }

        }

    if (data.get_NumBytes() != expectedSize) {
        Log.i(TAG, "Attachment size mismatch.");
        return;
        }

    success = data.WriteFile("downloaded-attachment.bin");
    if (success != true) {
        Log.i(TAG, "Could not save the attachment.");
        return;
        }

    Log.i(TAG, "Saved " + String.valueOf(data.get_NumBytes()) + " attachment bytes.");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}