Users.history: list

Requires authorization

Lists the history of all changes to the given mailbox. History results are returned in chronological order (increasing historyId). Try it now or see an example.

Request

HTTP request

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

Parameters

Parameter name Value Description
Path parameters
userId string The user's email address. The special value me can be used to indicate the authenticated user.
Optional query parameters
historyTypes string History types to be returned by the function

Acceptable values are:
  • "labelAdded"
  • "labelRemoved"
  • "messageAdded"
  • "messageDeleted"
labelId string Only return messages with a label matching the ID.
maxResults unsigned integer The maximum number of history records to return.
pageToken string Page token to retrieve a specific page of results in the list.
startHistoryId unsigned long Required. Returns history records after the specified startHistoryId. The supplied startHistoryId should be obtained from the historyId of a message, thread, or previous list response. History IDs increase chronologically but are not contiguous with random gaps in between valid IDs. Supplying an invalid or out of date startHistoryId typically returns an HTTP 404 error code. A historyId is typically valid for at least a week, but in some rare circumstances may be valid for only a few hours. If you receive an HTTP 404 error response, your application should perform a full sync. If you receive no nextPageToken in the response, there are no updates to retrieve and you can store the returned historyId for a future request.

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 response body with the following structure:

{
  "history": [
    {
      "id": unsigned long,
      "messages": [
        users.messages Resource
      ],
      "messagesAdded": [
        {
          "message": users.messages Resource
        }
      ],
      "messagesDeleted": [
        {
          "message": users.messages Resource
        }
      ],
      "labelsAdded": [
        {
          "message": users.messages Resource,
          "labelIds": [
            string
          ]
        }
      ],
      "labelsRemoved": [
        {
          "message": users.messages Resource,
          "labelIds": [
            string
          ]
        }
      ]
    }
  ],
  "nextPageToken": string,
  "historyId": unsigned long
}
Property name Value Description Notes
history[] list List of history records. Any messages contained in the response will typically only have id and threadId fields populated.
history[].id unsigned long The mailbox sequence ID.
history[].messages[] list List of messages changed in this history record. The fields for specific change types, such as messagesAdded may duplicate messages in this field. We recommend using the specific change-type fields instead of this.
nextPageToken string Page token to retrieve the next page of results in the list.
historyId unsigned long The ID of the mailbox's current history record.
history[].messagesAdded[] list Messages added to the mailbox in this history record.
history[].messagesAdded[].message nested object
history[].messagesDeleted[] list Messages deleted (not Trashed) from the mailbox in this history record.
history[].messagesDeleted[].message nested object
history[].labelsAdded[] list Labels added to messages in this history record.
history[].labelsAdded[].message nested object
history[].labelsAdded[].labelIds[] list Label IDs added to the message.
history[].labelsRemoved[] list Labels removed from messages in this history record.
history[].labelsRemoved[].message nested object
history[].labelsRemoved[].labelIds[] list Label IDs removed from the message.

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.services.gmail.Gmail;
import com.google.api.services.gmail.model.History;
import com.google.api.services.gmail.model.ListHistoryResponse;

import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

// ...

public class MyClass {

  // ...

  /**
   * Print message changes.
   *
   * @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 startHistoryId Only return Histories at or after startHistoryId.
   * @throws IOException
   */
  public static void listHistory(Gmail service, String userId, BigInteger startHistoryId)
      throws IOException {
    List<History> histories = new ArrayList<History>();
    ListHistoryResponse response = service.users().history().list(userId)
        .setStartHistoryId(startHistoryId).execute();
    while (response.getHistory() != null) {
      histories.addAll(response.getHistory());
      if (response.getNextPageToken() != null) {
        String pageToken = response.getNextPageToken();
        response = service.users().history().list(userId).setPageToken(pageToken)
            .setStartHistoryId(startHistoryId).execute();
      } else {
        break;
      }
    }

    for (History history : histories) {
      System.out.println(history.toPrettyString());
    }
  }

  // ...

}

.NET

Uses the .NET client library.

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

using System.Collections.Generic;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// List History of all changes to the user's mailbox.
  /// </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="startHistoryId">Only return changes at or after startHistoryId.</param>
  public static List<History> ListHistory(GmailService service, String userId, ulong startHistoryId)
  {
      List<History> result = new List<History>();
      UsersResource.HistoryResource.ListRequest request = service.Users.History.List(userId);
      request.StartHistoryId = startHistoryId;

      do
      {
          try
          {
              ListHistoryResponse response = request.Execute();
              if (response.History != null)
              {
                  result.AddRange(response.History);
              }
              request.PageToken = response.NextPageToken;
          }
          catch (Exception e)
          {
              Console.WriteLine("An error occurred: " + e.Message);
          }
      } while (!String.IsNullOrEmpty(request.PageToken));

      return result;
  }

  // ...

}

PHP

Does not use a client library.

/**
 * List all Message changes to the given mailbox. History results are
 * returned in chronological order (of increasing historyId).
 *
 * @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  integer $startHistoryId Only return Histories at or after
 * startHistoryId.
 * @return Array of Histories.
 */
function listHistory($service, $userId, $startHistoryId) {
  $opt_param = array('startHistoryId' => $startHistoryId);
  $pageToken = NULL;
  $histories = array();

  do {
    try {
      if ($pageToken) {
        $opt_param['pageToken'] = $pageToken;
      }
      $historyResponse = $service->users_history->listUsersHistory($userId, $opt_param);
      if ($historyResponse->getHistory()) {
        $histories = array_merge($histories, $historyResponse->getHistory());
        $pageToken = $historyResponse->getNextPageToken();
      }
    } catch (Exception $e) {
      print 'An error occurred: ' . $e->getMessage();
    }
  } while ($pageToken);


  return $histories;
}

Python

Uses the Python client library.

"""Get history from 'sinceHistoryId' to present.
"""

from apiclient import errors


def ListHistory(service, user_id, start_history_id='1'):
  """List History of all changes to the user's mailbox.

  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.
    start_history_id: Only return Histories at or after start_history_id.

  Returns:
    A list of mailbox changes that occurred after the start_history_id.
  """
  try:
    history = (service.users().history().list(userId=user_id,
                                              startHistoryId=start_history_id)
               .execute())
    changes = history['history'] if 'history' in history else []
    while 'nextPageToken' in history:
      page_token = history['nextPageToken']
      history = (service.users().history().list(userId=user_id,
                                        startHistoryId=start_history_id,
                                        pageToken=page_token).execute())
      changes.extend(history['history'])

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

JavaScript

Does not use a client library.

/**
 * Retrieve all Message changes to the given mailbox. History results are
 * returned in chronological order (of increasing historyId).
 *
 * @param  {String} userId User's email address. The special value 'me'
 * can be used to indicate the authenticated user.
 * @param  {String} startHistoryId Only return Histories at or after startHistoryId.
 * @param  {Function} callback Function to call when the request is complete.
 */
function listHistory(userId, startHistoryId, callback) {
  var getPageOfHistory = function(request, result) {
    request.execute(function(resp) {
      result = result.concat(resp.history);
      var nextPageToken = resp.nextPageToken;
      if (nextPageToken) {
        request = gapi.client.gmail.users.history.list({
          'userId': userId,
          'startHistoryId': startHistoryId,
          'pageToken': nextPageToken
        });
        getPageOfHistory(request, result);
      } else {
        callback(result);
      }
    });
  };
  var request = gapi.client.gmail.users.history.list({
    'startHistoryId': startHistoryId
  });
  getPageOfHistory(request, []);
}

Try it!

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

Send feedback about...