Users.messages.attachments: get

Gets the specified message attachment. Try it now or see an example.


HTTP request



Parameter name Value Description
Path parameters
id string The ID of the attachment.
messageId string The ID of the message containing the attachment.
userId string The user's email address. The special value me can be used to indicate the authenticated user.


This request requires authorization with at least one of the following scopes:


For more information, see the authentication and authorization page.

Request body

Do not supply a request body with this method.


If successful, this method returns a Users.messages.attachments resource in the response body.


Note: The code examples available for this method do not represent all supported programming languages (see the client libraries page for a list of supported languages).


Uses the Java client library.


import java.util.List;

// ...

public class MyClass {

  // ...

   * Get the attachments in a given email.
   * @param service Authorized Gmail API instance.
   * @param userId User's email address. The special value "me"
   * can be used to indicate the authenticated user.
   * @param messageId ID of Message containing attachment..
   * @throws IOException
  public static void getAttachments(Gmail service, String userId, String messageId)
      throws IOException {
    Message message = service.users().messages().get(userId, messageId).execute();
    List<MessagePart> parts = message.getPayload().getParts();
    for (MessagePart part : parts) {
      if (part.getFilename() != null && part.getFilename().length() > 0) {
        String filename = part.getFilename();
        String attId = part.getBody().getAttachmentId();
        MessagePartBody attachPart = service.users().messages().attachment().
            get(userId, messageId, attId).execute();

        Base64 base64Url = new Base64(true);
        byte[] fileByteArray = base64url.decodeBase64(attachPart.getData());
        FileOutputStream fileOutFile =
            new FileOutputStream("directory_to_store_attachments" + filename);

  // ...



Uses the .NET client library.

using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;

using System;
using System.Collections.Generic;
using System.IO;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Get and store attachment from Message with given ID.
  /// </summary>
  /// <param name="service">Gmail API service instance.</param>
  /// <param name="userId">User's email address. The special value "me"
  /// can be used to indicate the authenticated user.</param>
  /// <param name="messageId">ID of Message containing attachment.</param>
  /// <param name="outputDir">Directory used to store attachments.</param>
  public static void GetAttachments(GmailService service, String userId, String messageId, String outputDir)
          Message message = service.Users.Messages.Get(userId, messageId).Execute();
          IList<MessagePart> parts = message.Payload.Parts;
          foreach (MessagePart part in parts)
              if (!String.IsNullOrEmpty(part.Filename))
                  String attId = part.Body.AttachmentId;
                  MessagePartBody attachPart = service.Users.Messages.Attachments.Get(userId, messageId, attId).Execute();

                  // Converting from RFC 4648 base64 to base64url encoding
                  // see
                  String attachData = attachPart.Data.Replace('-', '+');
                  attachData = attachData.Replace('_', '/');

                  byte[] data = Convert.FromBase64String(attachData);
                  File.WriteAllBytes(Path.Combine(outputDir, part.Filename), data);
      catch (Exception e)
          Console.WriteLine("An error occurred: " + e.Message);

  // ...



Uses the Python client library.

"""Retrieve an attachment from a Message.

import base64
from apiclient import errors

def GetAttachments(service, user_id, msg_id, store_dir):
  """Get and store attachment from Message with given id.

    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me"
    can be used to indicate the authenticated user.
    msg_id: ID of Message containing attachment.
    store_dir: The directory used to store attachments.
    message = service.users().messages().get(userId=user_id, id=msg_id).execute()

    for part in message['payload']['parts']:
      if part['filename']:

        file_data = base64.urlsafe_b64decode(part['body']['data']

        path = ''.join([store_dir, part['filename']])

        f = open(path, 'w')

  except errors.HttpError, error:
    print 'An error occurred: %s' % error


Does not use a client library.

 * Get Attachments from a given Message.
 * @param  {String} userId User's email address. The special value 'me'
 * can be used to indicate the authenticated user.
 * @param  {String} messageId ID of Message with attachments.
 * @param  {Function} callback Function to call when the request is complete.
function getAttachments(userId, message, callback) {
  var parts =;
  for (var i = 0; i < parts.length; i++) {
    var part = parts[i];
    if (part.filename && part.filename.length > 0) {
      var attachId = part.body.attachmentId;
      var request ={
        'id': attachId,
        'userId': userId
      request.execute(function(attachment) {
        callback(part.filename, part.mimeType, attachment);

Try it!

Use the APIs Explorer below to call this method on live data and see the response.