Users.messages: get

Requires authorization

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

Request

HTTP request

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

Parameters

Parameter name Value Description
Path parameters
id string The ID of the message to retrieve.
userId string The user's email address. The special value me can be used to indicate the authenticated user.
Optional query parameters
format string The format to return the message in.

Acceptable values are:
  • "full": Returns the full email message data with body content parsed in the payload field; the raw field is not used. (default)
  • "metadata": Returns only email message ID, labels, and email headers.
  • "minimal": Returns only email message ID and labels; does not return the email headers, body, or payload.
  • "raw": Returns the full email message data with body content in the raw field as a base64url encoded string; the payload field is not used.
metadataHeaders[] list When given and format is METADATA, only include headers specified.

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
https://www.googleapis.com/auth/gmail.metadata

Request body

Do not supply a request body with this method.

Response

If successful, this method returns a Users.messages 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 java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

// ...

public class MyClass {

  // ...


  /**
   * Get Message with given ID.
   *
   * @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 to retrieve.
   * @return Message Retrieved Message.
   * @throws IOException
   */
  public static Message getMessage(Gmail service, String userId, String messageId)
      throws IOException {
    Message message = service.users().messages().get(userId, messageId).execute();

    System.out.println("Message snippet: " + message.getSnippet());

    return message;
  }

  /**
   * Get a Message and use it to create a MimeMessage.
   *
   * @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 to retrieve.
   * @return MimeMessage MimeMessage populated from retrieved Message.
   * @throws IOException
   * @throws MessagingException
   */
  public static MimeMessage getMimeMessage(Gmail service, String userId, String messageId)
      throws IOException, MessagingException {
    Message message = service.users().messages().get(userId, messageId).setFormat("raw").execute();

    Base64 base64Url = new Base64(true);
    byte[] emailBytes = base64Url.decodeBase64(message.getRaw());

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));

    return email;
  }

  // ...

}

.NET

Uses the .NET client library.

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

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Retrieve a Message by 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 to retrieve.</param>
  public static Message GetMessage(GmailService service, String userId, String messageId)
  {
      try
      {
          return service.Users.Messages.Get(userId, messageId).Execute();
      }
      catch (Exception e)
      {
          Console.WriteLine("An error occurred: " + e.Message);
      }

      return null;
  }

  // ...

}

PHP

Does not use a client library.

/**
 * Get Message with given ID.
 *
 * @param  Google_Service_Gmail $service Authorized Gmail API instance.
 * @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 to get.
 * @return Google_Service_Gmail_Message Message retrieved.
 */
function getMessage($service, $userId, $messageId) {
  try {
    $message = $service->users_messages->get($userId, $messageId);
    print 'Message with ID: ' . $message->getId() . ' retrieved.';
    return $message;
  } catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
  }
}

Python

Uses the Python client library.

"""Get Message with given ID.
"""

import base64
import email
from apiclient import errors

def GetMessage(service, user_id, msg_id):
  """Get a 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: The ID of the Message required.

  Returns:
    A Message.
  """
  try:
    message = service.users().messages().get(userId=user_id, id=msg_id).execute()

    print 'Message snippet: %s' % message['snippet']

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


def GetMimeMessage(service, user_id, msg_id):
  """Get a Message and use it to create a MIME Message.

  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: The ID of the Message required.

  Returns:
    A MIME Message, consisting of data from Message.
  """
  try:
    message = service.users().messages().get(userId=user_id, id=msg_id,
                                             format='raw').execute()

    print 'Message snippet: %s' % message['snippet']

    msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))

    mime_msg = email.message_from_string(msg_str)

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

JavaScript

Does not use a client library.

/**
 * Get Message with given ID.
 *
 * @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 to get.
 * @param  {Function} callback Function to call when the request is complete.
 */
function getMessage(userId, messageId, callback) {
  var request = gapi.client.gmail.users.messages.get({
    'userId': userId,
    'id': messageId
  });
  request.execute(callback);
}

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.