Users.threads: list

Requires authorization

Lists the threads in the user's mailbox. Try it now or see an example.

Request

HTTP request

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

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
includeSpamTrash boolean Include threads from SPAM and TRASH in the results. (Default: false)
labelIds string Only return threads with labels that match all of the specified label IDs.
maxResults unsigned integer Maximum number of threads to return.
pageToken string Page token to retrieve a specific page of results in the list.
q string Only return threads matching the specified query. Supports the same query format as the Gmail search box. For example, "from:someuser@example.com rfc822msgid: is:unread". Parameter cannot be used when accessing the api using the gmail.metadata scope.

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:

{
  "threads": [
    users.threads Resource
  ],
  "nextPageToken": string,
  "resultSizeEstimate": unsigned integer
}
Property name Value Description Notes
threads[] list List of threads.
nextPageToken string Page token to retrieve the next page of results in the list.
resultSizeEstimate unsigned integer Estimated total number of results.

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.ListThreadsResponse;
import com.google.api.services.gmail.model.Thread;

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

// ...

public class MyClass {

  // ...

  /**
   * List all Threads of the user's mailbox matching the query.
   *
   * @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 query String used to filter the Threads listed.
   * @throws IOException
   */
  public static void listThreadsMatchingQuery (Gmail service, String userId,
      String query) throws IOException {
    ListThreadsResponse response = service.users().threads().list(userId).setQ(query).execute();
    List<Thread> threads = new ArrayList<Thread>();
    while(response.getThreads() != null) {
      threads.addAll(response.getThreads());
      if(response.getNextPageToken() != null) {
        String pageToken = response.getNextPageToken();
        response = service.users().threads().list(userId).setQ(query).setPageToken(pageToken).execute();
      } else {
        break;
      }
    }

    for(Thread thread : threads) {
      System.out.println(thread.toPrettyString());
    }
  }

  /**
   * List all Threads of the user's mailbox with labelIds applied.
   *
   * @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 labelIds String used to filter the Threads listed.
   * @throws IOException
   */
  public static void listThreadsWithLabels (Gmail service, String userId,
      List<String> labelIds) throws IOException {
    ListThreadsResponse response = service.users().threads().list(userId).setLabelIds(labelIds).execute();
    List<Thread> threads = new ArrayList<Thread>();
    while(response.getThreads() != null) {
      threads.addAll(response.getThreads());
      if(response.getNextPageToken() != null) {
        String pageToken = response.getNextPageToken();
        response = service.users().threads().list(userId).setLabelIds(labelIds)
            .setPageToken(pageToken).execute();
      } else {
        break;
      }
    }

    for(Thread thread : threads) {
      System.out.println(thread.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 all message threads of 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>
  public static List<Thread> ListThreads(GmailService service, String userId)
  {
      List<Thread> result = new List<Thread>();
      UsersResource.ThreadsResource.ListRequest request = service.Users.Threads.List(userId);

      do
      {
          try
          {
              ListThreadsResponse response = request.Execute();
              result.AddRange(response.Threads);
              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.

/**
 * Get all Threads in the user's mailbox.
 *
 * @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.
 * @return array Array of Threads.
 */
function listThreads($service, $userId) {
  $threads = array();
  $pageToken = NULL;
  do {
    try {
      $opt_param = array();
      if ($pageToken) {
        $opt_param['pageToken'] = $pageToken;
      }
      $threadsResponse = $service->users_threads->listUsersThreads($userId, $opt_param);
      if ($threadsResponse->getThreads()) {
        $threads = array_merge($threads, $threadsResponse->getThreads());
        $pageToken = $threadsResponse->getNextPageToken();
      }
    } catch (Exception $e) {
      print 'An error occurred: ' . $e->getMessage();
      $pageToken = NULL;
    }
  } while ($pageToken);

  foreach ($threads as $thread) {
    print 'Thread with ID: ' . $thread->getId() . '<br/>';
  }

  return $threads;
}

Python

Uses the Python client library.

"""Get a list of Threads from the user's mailbox.
"""

from apiclient import errors


def ListThreadsMatchingQuery(service, user_id, query=''):
  """List all Threads of the user's mailbox matching the query.

  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.
    query: String used to filter messages returned.
           Eg.- 'label:UNREAD' for unread messages only.

  Returns:
    List of threads that match the criteria of the query. Note that the returned
    list contains Thread IDs, you must use get with the appropriate
    ID to get the details for a Thread.
  """
  try:
    response = service.users().threads().list(userId=user_id, q=query).execute()
    threads = []
    if 'threads' in response:
      threads.extend(response['threads'])

    while 'nextPageToken' in response:
      page_token = response['nextPageToken']
      response = service.users().threads().list(userId=user_id, q=query,
                                        pageToken=page_token).execute()
      threads.extend(response['threads'])

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


def ListThreadsWithLabels(service, user_id, label_ids=[]):
  """List all Threads of the user's mailbox with label_ids applied.

  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.
    label_ids: Only return Threads with these labelIds applied.

  Returns:
    List of threads that match the criteria of the query. Note that the returned
    list contains Thread IDs, you must use get with the appropriate
    ID to get the details for a Thread.
  """
  try:
    response = service.users().threads().list(userId=user_id,
                                              labelIds=label_ids).execute()
    threads = []
    if 'threads' in response:
      threads.extend(response['threads'])

    while 'nextPageToken' in response:
      page_token = response['nextPageToken']
      response = service.users().threads().list(userId=user_id,
                                                labelIds=label_ids,
                                                pageToken=page_token).execute()
      threads.extend(response['threads'])

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

JavaScript

Does not use a client library.

/**
 * Retrieve Threads in the user's mailbox matching query.
 *
 * @param  {String} userId User's email address. The special value 'me'
 * can be used to indicate the authenticated user.
 * @param  {String} query String used to filter the Threads listed.
 * @param  {Function} callback Function to call when the request is complete.
 */
function listThreads(userId, query, callback) {
  var getPageOfThreads = function(request, result) {
    request.execute(function (resp) {
      result = result.concat(resp.threads);
      var nextPageToken = resp.nextPageToken;
      if (nextPageToken) {
        request = gapi.client.gmail.users.threads.list({
          'userId': userId,
          'q': query,
          'pageToken': nextPageToken
        });
        getPageOfThreads(request, result);
      } else {
        callback(result);
      }
    });
  };
  var request = gapi.client.gmail.users.threads.list({
    'userId': userId,
    'q': query
  });
  getPageOfThreads(request, []);
}

Try it!

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

Send feedback about...