Elenca i messaggi di Gmail

Questo documento spiega come chiamare il metodo dell'API Gmail messages.list.

Il metodo restituisce un array di oggetti messages di Gmail che contengono id e threadId del messaggio. Per recuperare i dettagli completi del messaggio, utilizza il messages.get metodo.

Gli oggetti messages restituiti sono elencati in ordine cronologico inverso (i più recenti per primi).

Prerequisiti

Python

Un progetto Google Cloud con l'API Gmail abilitata. Per i passaggi, completa la guida rapida all'API Gmail in Python.

Elenco di messaggi

Il metodo messages.list supporta diversi parametri di query per filtrare i messaggi:

  • maxResults: numero massimo di messaggi da restituire (il valore predefinito è 100, il massimo è 500).
  • pageToken: token per recuperare una pagina specifica di risultati.
  • q: stringa di query per filtrare i messaggi, ad esempio from:someuser@example.com is:unread.
  • labelIds: restituisce solo i messaggi con etichette che corrispondono a tutti gli ID etichetta specificati.
  • includeSpamTrash: include i messaggi da SPAM e TRASH nei risultati.

Esempio di codice

Python

Il seguente esempio di codice mostra come elencare i messaggi per l'utente Gmail autenticato. Il codice gestisce la paginazione per recuperare tutti i messaggi che corrispondono alla query.

gmail/snippet/list_messages.py
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]


def main():
    """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.
    if os.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.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.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 run
        with open("token.json", "w") as token:
            token.write(creds.to_json())

    try:
        # Call the Gmail API
        service = build("gmail", "v1", credentials=creds)
        results = (
            service.users().messages().list(userId="me", labelIds=["INBOX"]).execute()
        )
        messages = results.get("messages", [])

        if not messages:
            print("No messages found.")
            return

        print("Messages:")
        for message in messages:
            print(f'Message ID: {message["id"]}')
            msg = (
                service.users().messages().get(userId="me", id=message["id"]).execute()
            )
            print(f'  Subject: {msg["snippet"]}')

    except HttpError as error:
        # TODO(developer) - Handle errors from gmail API.
        print(f"An error occurred: {error}")


if __name__ == "__main__":
    main()

Il metodo messages.list restituisce un corpo della risposta che contiene quanto segue:

  • messages[]: un array di risorse Message.
  • nextPageToken: per le richieste con più pagine di risultati, un token che può essere utilizzato con le chiamate successive per elencare altri messaggi.
  • resultSizeEstimate: un numero totale stimato di risultati.

Per recuperare i contenuti e i metadati completi del messaggio, utilizza il message.id campo per chiamare il messages.get metodo.