Wyświetlanie listy wiadomości z Gmaila

Na tej stronie dowiesz się, jak wywołać metodę users.messages.list interfejsu Gmail API.

Metoda zwraca tablicę zasobów Gmail Message, które zawierają wiadomość id i threadId. Aby pobrać pełne szczegóły wiadomości, użyj metody users.messages.get.

Wymagania wstępne

Python

projekt Google Cloud z włączonym interfejsem Gmail API; Aby wykonać te czynności, zapoznaj się z krótkim przewodnikiem po interfejsie Gmail API w Pythonie.

Wyświetlanie listy wiadomości

Metoda users.messages.list obsługuje kilka parametrów zapytania, które umożliwiają filtrowanie wiadomości:

  • maxResults: maksymalna liczba wiadomości do zwrócenia (domyślnie 100, maksymalnie 500).
  • pageToken: token do pobierania konkretnej strony wyników.
  • q: ciąg zapytania do filtrowania wiadomości, np. from:someuser@example.com is:unread".
  • labelIds: zwraca tylko wiadomości z etykietami, które pasują do wszystkich podanych identyfikatorów etykiet.
  • includeSpamTrash: uwzględnia w wynikach wiadomości od nadawców SPAMTRASH.

Przykładowy kod

Python

Poniższy przykład kodu pokazuje, jak wyświetlić listę wiadomości uwierzytelnionego użytkownika Gmaila. Kod obsługuje stronicowanie, aby pobrać wszystkie wiadomości pasujące do zapytania.

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()

Metoda users.messages.list zwraca treść odpowiedzi, która zawiera:

  • messages[]: tablica zasobów Message.
  • nextPageToken: w przypadku żądań z wieloma stronami wyników token, którego można użyć w kolejnych wywołaniach, aby wyświetlić więcej wiadomości.
  • resultSizeEstimate: szacunkowa łączna liczba wyników.

Aby pobrać pełną treść wiadomości i metadane, użyj pola message.id, aby wywołać metodę users.messages.get.