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

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  var success = false;

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

  final token = CkJsonObject();
  try {
    token.loadFile('gmail-token.json');
  } on ChilkatException {
    print('Could not read gmail-token.json from the private working directory.');
    return;
  }

  if ((token.jsonTypeOf('access_token') != 1) || (token.stringOfEquals('access_token', '', true))) {
    print('An OAuth access token is required.');
    return;
  }

  final http = CkHttp();
  http.requireSslCertVerify = true;
  http.authToken = token.stringOf('access_token');
  final resp = CkHttpResponse();
  final reply = CkJsonObject();
  final messageId = 'GMAIL_MESSAGE_ID';
  final filename = 'attachment.pdf';
  final messageUrl = CkStringBuilder();
  messageUrl.append('https://gmail.googleapis.com/gmail/v1/users/me/messages/');
  messageUrl.append(http.urlEncode(messageId));
  final url = CkStringBuilder();
  url.append(messageUrl.getAsString());
  url.append('?format=full');
  success = true;
  try {
    http.httpNoBody('GET', url.getAsString(), resp);
  } on ChilkatException {
    success = false;
  }
  if (resp.statusCode == 0) {
    print('Gmail did not return an HTTP response.');
    return;
  }

  if ((!success) || ((resp.statusCode < 200) || (resp.statusCode >= 300))) {
    print('Gmail HTTP ${resp.statusCode}');
    try {
      reply.load(resp.bodyStr);
      print(reply.stringOf('error.message'));
    } on ChilkatException {
      // reply.load() failed; continue anyway.
    }

    return;
  }

  try {
    reply.load(resp.bodyStr);
  } on ChilkatException {
    print('Expected a Gmail JSON response.');
    return;
  }

  final paths = CkStringTable();
  try {
    paths.append('payload');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final partVar = CkJsonObject();
  final selected = CkJsonObject();
  final childPath = CkStringBuilder();
  var matches = 0;
  var p = 0;
  while (p < paths.count) {
    try {
      reply.objectOf2(paths.stringAt(p), partVar);
    } on ChilkatException catch (e) {
      print(e.lastErrorText);
      return;
    }

    if (partVar.stringOfEquals('filename', filename, true)) {
      matches++;
      try {
        partVar.makeCopy(selected);
      } on ChilkatException catch (e) {
        print(e.lastErrorText);
        return;
      }

      print('Matching MIME part: ${paths.stringAt(p)}');
    }

    var j = 0;
    while (j < partVar.sizeOfArray('parts')) {
      childPath.setString(paths.stringAt(p));
      childPath.append('.parts[');
      childPath.appendInt(j);
      childPath.append(']');
      try {
        paths.append(childPath.getAsString());
      } on ChilkatException catch (e) {
        print(e.lastErrorText);
        return;
      }

      j++;
    }

    p++;
  }

  if (matches != 1) {
    print('Expected one filename match. Matches: $matches');
    return;
  }

  final body = CkJsonObject();
  try {
    selected.objectOf2('body', body);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  if (body.jsonTypeOf('size') != 2) {
    print('The selected part has no byte count.');
    return;
  }

  final expectedSize = body.intOf('size');
  if (body.jsonTypeOf('attachmentId') == 1) {
    url.setString(messageUrl.getAsString());
    url.append('/attachments/');
    url.append(http.urlEncode(body.stringOf('attachmentId')));
    success = true;
    try {
      http.httpNoBody('GET', url.getAsString(), resp);
    } on ChilkatException {
      success = false;
    }
    if (resp.statusCode == 0) {
      print('Gmail did not return an HTTP response.');
      return;
    }

    if ((!success) || ((resp.statusCode < 200) || (resp.statusCode >= 300))) {
      print('Gmail HTTP ${resp.statusCode}');
      try {
        reply.load(resp.bodyStr);
        print(reply.stringOf('error.message'));
      } on ChilkatException {
        // reply.load() failed; continue anyway.
      }

      return;
    }

    try {
      reply.load(resp.bodyStr);
    } on ChilkatException {
      print('Expected a Gmail JSON response.');
      return;
    }

    try {
      reply.makeCopy(body);
    } on ChilkatException catch (e) {
      print(e.lastErrorText);
      return;
    }
  }

  if (body.jsonTypeOf('data') != 1) {
    print('The attachment response has no data.');
    return;
  }

  final data = CkBinData();
  if (!body.stringOfEquals('data', '', true)) {
    try {
      body.bytesOf('data', 'base64url', data);
    } on ChilkatException catch (e) {
      print(e.lastErrorText);
      return;
    }
  }

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

  try {
    data.writeFile('downloaded-attachment.bin');
  } on ChilkatException {
    print('Could not save the attachment.');
    return;
  }

  print('Saved ${data.numBytes} attachment bytes.');
}