Requires authorization
Lists the messages in the user's mailbox. Try it now or see an example.
Request
HTTP request
GET https://www.googleapis.com/gmail/v1/users/userId/messages
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 messages from SPAM and TRASH
in the results.
(Default: false)
|
labelIds[] |
list |
Only return messages with labels that match all of the specified label IDs. |
maxResults |
unsigned integer |
Maximum number of messages to return. |
pageToken |
string |
Page token to retrieve a specific page of results in the list. |
q |
string |
Only return messages matching the specified query. Supports the same
query format as the Gmail search box. For example,
"from:someuser@example.com rfc822msgid:. 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:
{
"messages": [
users.messages Resource
],
"nextPageToken": string,
"resultSizeEstimate": unsigned integer
}
| Property name | Value | Description | Notes |
|---|---|---|---|
messages[] |
list |
List of messages. | |
nextPageToken |
string |
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.ListMessagesResponse;
import com.google.api.services.gmail.model.Message;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
// ...
public class MyClass {
// ...
/**
* List all Messages 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 Messages listed.
* @throws IOException
*/
public static List<Message> listMessagesMatchingQuery(Gmail service, String userId,
String query) throws IOException {
ListMessagesResponse response = service.users().messages().list(userId).setQ(query).execute();
List<Message> messages = new ArrayList<Message>();
while (response.getMessages() != null) {
messages.addAll(response.getMessages());
if (response.getNextPageToken() != null) {
String pageToken = response.getNextPageToken();
response = service.users().messages().list(userId).setQ(query)
.setPageToken(pageToken).execute();
} else {
break;
}
}
for (Message message : messages) {
System.out.println(message.toPrettyString());
}
return messages;
}
/**
* List all Messages 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 Only return Messages with these labelIds applied.
* @throws IOException
*/
public static List<Message> listMessagesWithLabels(Gmail service, String userId,
List<String> labelIds) throws IOException {
ListMessagesResponse response = service.users().messages().list(userId)
.setLabelIds(labelIds).execute();
List<Message> messages = new ArrayList<Message>();
while (response.getMessages() != null) {
messages.addAll(response.getMessages());
if (response.getNextPageToken() != null) {
String pageToken = response.getNextPageToken();
response = service.users().messages().list(userId).setLabelIds(labelIds)
.setPageToken(pageToken).execute();
} else {
break;
}
}
for (Message message : messages) {
System.out.println(message.toPrettyString());
}
return messages;
}
// ...
}
.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 Messages of the user's mailbox matching the query.
/// </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="query">String used to filter Messages returned.</param>
public static List<Message> ListMessages(GmailService service, String userId, String query)
{
List<Message> result = new List<Message>();
UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
request.Q = query;
do
{
try
{
ListMessagesResponse response = request.Execute();
result.AddRange(response.Messages);
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 list of Messages in 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 Messages.
*/
function listMessages($service, $userId) {
$pageToken = NULL;
$messages = array();
$opt_param = array();
do {
try {
if ($pageToken) {
$opt_param['pageToken'] = $pageToken;
}
$messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);
if ($messagesResponse->getMessages()) {
$messages = array_merge($messages, $messagesResponse->getMessages());
$pageToken = $messagesResponse->getNextPageToken();
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
} while ($pageToken);
foreach ($messages as $message) {
print 'Message with ID: ' . $message->getId() . '<br/>';
}
return $messages;
}
Python
Uses the Python client library.
"""Get a list of Messages from the user's mailbox.
"""
from apiclient import errors
def ListMessagesMatchingQuery(service, user_id, query=''):
"""List all Messages 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.- 'from:user@some_domain.com' for Messages from a particular sender.
Returns:
List of Messages that match the criteria of the query. Note that the
returned list contains Message IDs, you must use get with the
appropriate ID to get the details of a Message.
"""
try:
response = service.users().messages().list(userId=user_id,
q=query).execute()
messages = []
if 'messages' in response:
messages.extend(response['messages'])
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId=user_id, q=query,
pageToken=page_token).execute()
messages.extend(response['messages'])
return messages
except errors.HttpError, error:
print 'An error occurred: %s' % error
def ListMessagesWithLabels(service, user_id, label_ids=[]):
"""List all Messages 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 Messages with these labelIds applied.
Returns:
List of Messages that have all required Labels applied. Note that the
returned list contains Message IDs, you must use get with the
appropriate id to get the details of a Message.
"""
try:
response = service.users().messages().list(userId=user_id,
labelIds=label_ids).execute()
messages = []
if 'messages' in response:
messages.extend(response['messages'])
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId=user_id,
labelIds=label_ids,
pageToken=page_token).execute()
messages.extend(response['messages'])
return messages
except errors.HttpError, error:
print 'An error occurred: %s' % error
JavaScript
Does not use a client library.
/**
* Retrieve Messages in 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 Messages listed.
* @param {Function} callback Function to call when the request is complete.
*/
function listMessages(userId, query, callback) {
var getPageOfMessages = function(request, result) {
request.execute(function(resp) {
result = result.concat(resp.messages);
var nextPageToken = resp.nextPageToken;
if (nextPageToken) {
request = gapi.client.gmail.users.messages.list({
'userId': userId,
'pageToken': nextPageToken,
'q': query
});
getPageOfMessages(request, result);
} else {
callback(result);
}
});
};
var initialRequest = gapi.client.gmail.users.messages.list({
'userId': userId,
'q': query
});
getPageOfMessages(initialRequest, []);
}
Try it!
Use the APIs Explorer below to call this method on live data and see the response.