Users.messages.attachments: get

Requires authorization

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

Request

HTTP request

GET https://www.googleapis.com/gmail/v1/users/userId/messages/messageId/attachments/id

Parameters

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.

Authorization

This request requires authorization with at least one of the following scopes (read more about authentication and authorization).

Scope
https://mail.google.com/
https://www.googleapis.com/auth/gmail.modify
https://www.googleapis.com/auth/gmail.readonly

Request body

Do not supply a request body with this method.

Response

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

Examples

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).

Java

Uses the Java client library.

import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import com.google.api.services.gmail.model.MessagePart;
import com.google.api.services.gmail.model.MessagePartBody;

import java.io.FileOutputStream;
import java.io.IOException;
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);
        fileOutFile.write(fileByteArray);
        fileOutFile.close();
      }
    }
  }

  // ...

}

.NET

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)
  {
      try
      {
          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 http://en.wikipedia.org/wiki/Base64#Implementations_and_history
                  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);
      }
  }

  // ...

}

Python

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.

  Args:
    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.
  """
  try:
    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']
                                             .encode('UTF-8'))

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

        f = open(path, 'w')
        f.write(file_data)
        f.close()

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

JavaScript

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 = message.payload.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 = gapi.client.gmail.users.messages.attachments.get({
        'id': attachId,
        'messageId': message.id,
        '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.

Enviar comentarios sobre…

¿Necesitas ayuda? Visita nuestra página de asistencia.