Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En esta página, se explica cómo llamar al método users.messages.list de la API de Gmail.
El método devuelve un array de recursos Message de Gmail que contienen los campos id y threadId del mensaje. Para recuperar los detalles completos del mensaje, usa el método users.messages.get.
El método users.messages.list admite varios parámetros de consulta para filtrar los mensajes:
maxResults: Es la cantidad máxima de mensajes que se devolverán (el valor predeterminado es 100 y el máximo es 500).
pageToken: Token para recuperar una página específica de resultados.
q: Es la cadena de consulta para filtrar mensajes, como from:someuser@example.com is:unread".
labelIds: Solo devuelve mensajes con etiquetas que coincidan con todos los IDs de etiqueta especificados.
includeSpamTrash: Incluye mensajes de SPAM y TRASH en los resultados.
Muestra de código
Python
En el siguiente ejemplo de código, se muestra cómo enumerar los mensajes del usuario de Gmail autenticado. El código controla la paginación para recuperar todos los mensajes que coinciden con la consulta.
importos.pathfromgoogle.auth.transport.requestsimportRequestfromgoogle.oauth2.credentialsimportCredentialsfromgoogle_auth_oauthlib.flowimportInstalledAppFlowfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpError# If modifying these scopes, delete the file token.json.SCOPES=["https://www.googleapis.com/auth/gmail.readonly"]defmain():"""Shows basic usage of the Gmail API. Lists the user's Gmail messages. """creds=None# The file token.json stores the user's access and refresh tokens, and is# created automatically when the authorization flow completes for the first# time.ifos.path.exists("token.json"):creds=Credentials.from_authorized_user_file("token.json",SCOPES)# If there are no (valid) credentials available, let the user log in.ifnotcredsornotcreds.valid:ifcredsandcreds.expiredandcreds.refresh_token:creds.refresh(Request())else:flow=InstalledAppFlow.from_client_secrets_file("credentials.json",SCOPES)creds=flow.run_local_server(port=0)# Save the credentials for the next runwithopen("token.json","w")astoken:token.write(creds.to_json())try:# Call the Gmail APIservice=build("gmail","v1",credentials=creds)results=(service.users().messages().list(userId="me",labelIds=["INBOX"]).execute())messages=results.get("messages",[])ifnotmessages:print("No messages found.")returnprint("Messages:")formessageinmessages:print(f'Message ID: {message["id"]}')msg=(service.users().messages().get(userId="me",id=message["id"]).execute())print(f' Subject: {msg["snippet"]}')exceptHttpErroraserror:# TODO(developer) - Handle errors from gmail API.print(f"An error occurred: {error}")if__name__=="__main__":main()
El método users.messages.list devuelve un cuerpo de respuesta que contiene lo siguiente:
messages[]: Es un array de recursos Message.
nextPageToken: Para las solicitudes con varias páginas de resultados, es un token que se puede usar con llamadas posteriores para enumerar más mensajes.
resultSizeEstimate: Es la cantidad total estimada de resultados.
Para recuperar el contenido y los metadatos completos del mensaje, usa el campo message.id para llamar al método users.messages.get.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-01 (UTC)"],[],[],null,["# List Gmail messages\n\nThis page explains how to call the Gmail API's\n[`users.messages.list`](/workspace/gmail/api/reference/rest/v1/users.messages/list)\nmethod.\n\nThe method returns an array of Gmail `Message` resources that\ncontain the message `id` and `threadId`. To retrieve full message details, use\nthe\n[`users.messages.get`](/workspace/gmail/api/reference/rest/v1/users.messages/get)\nmethod.\n\nPrerequisites\n-------------\n\n### Python\n\nA Google Cloud project with the Gmail API enabled. For steps, complete\nthe\n[Gmail API Python quickstart](/workspace/gmail/api/quickstart/python).\n\nList messages\n-------------\n\nThe `users.messages.list` method supports several query parameters to filter the\nmessages:\n\n- `maxResults`: Maximum number of messages to return (defaults to 100, max 500).\n- `pageToken`: Token to retrieve a specific page of results.\n- `q`: Query string to filter messages, such as `from:someuser@example.com is:unread\"`.\n- `labelIds`: Only return messages with labels that match all specified label IDs.\n- `includeSpamTrash`: Include messages from `SPAM` and `TRASH` in the results.\n\n### Code sample\n\n### Python\n\nThe following code sample shows how to list messages for the authenticated\nGmail user. The code handles pagination to retrieve all\nmessages matching the query. \ngmail/snippet/list_messages.py \n[View on GitHub](https://github.com/googleworkspace/python-samples/blob/main/gmail/snippet/list_messages.py) \n\n```python\nimport os.path\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\n# If modifying these scopes, delete the file token.json.\nSCOPES = [\"https://www.googleapis.com/auth/gmail.readonly\"]\n\n\ndef main():\n \"\"\"Shows basic usage of the Gmail API.\n Lists the user's Gmail messages.\n \"\"\"\n creds = None\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists(\"token.json\"):\n creds = Credentials.from_authorized_user_file(\"token.json\", SCOPES)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\"credentials.json\", SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open(\"token.json\", \"w\") as token:\n token.write(creds.to_json())\n\n try:\n # Call the Gmail API\n service = build(\"gmail\", \"v1\", credentials=creds)\n results = (\n service.users().messages().list(userId=\"me\", labelIds=[\"INBOX\"]).execute()\n )\n messages = results.get(\"messages\", [])\n\n if not messages:\n print(\"No messages found.\")\n return\n\n print(\"Messages:\")\n for message in messages:\n print(f'Message ID: {message[\"id\"]}')\n msg = (\n service.users().messages().get(userId=\"me\", id=message[\"id\"]).execute()\n )\n print(f' Subject: {msg[\"snippet\"]}')\n\n except HttpError as error:\n # TODO(developer) - Handle errors from gmail API.\n print(f\"An error occurred: {error}\")\n\n\nif __name__ == \"__main__\":\n main()\n```\n\nThe `users.messages.list` method returns a response body that contains the\nfollowing:\n\n- `messages[]`: An array of `Message` resources.\n- `nextPageToken`: For requests with multiple pages of results, a token that can be used with a subsequent calls to list more messages.\n- `resultSizeEstimate`: An estimated total number of results.\n\nTo fetch the full message content and metadata, use the `message.id` field to\ncall the\n[`users.messages.get`](/workspace/gmail/api/reference/rest/v1/users.messages/get)\nmethod.\n\nRelated resources\n-----------------\n\n- [`users.messages.list`](/workspace/gmail/api/reference/rest/v1/users.messages/list)\n- [`users.messages.get`](/workspace/gmail/api/reference/rest/v1/users.messages/get)"]]