Gmail のメールを一覧表示する

このページでは、Gmail API の users.messages.list メソッドを呼び出す方法について説明します。

このメソッドは、メッセージ idthreadId を含む Gmail Message リソースの配列を返します。メッセージの詳細をすべて取得するには、users.messages.get メソッドを使用します。

前提条件

Python

Gmail API が有効になっている Google Cloud プロジェクト。手順については、Gmail API Python クイックスタートを完了してください。

メッセージの一覧表示

users.messages.list メソッドは、メッセージをフィルタするいくつかのクエリ パラメータをサポートしています。

  • maxResults: 返されるメッセージの最大数(デフォルトは 100、最大 500)。
  • pageToken: 結果の特定のページを取得するためのトークン。
  • q: メッセージをフィルタするクエリ文字列(from:someuser@example.com is:unread" など)。
  • labelIds: 指定されたすべてのラベル ID と一致するラベルを持つメッセージのみを返します。
  • includeSpamTrash: 結果に SPAMTRASH のメッセージを含めます。

コードサンプル

Python

次のコードサンプルは、認証済みの Gmail ユーザーのメッセージを一覧表示する方法を示しています。このコードは、クエリに一致するすべてのメッセージを取得するためにページネーションを処理します。

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

users.messages.list メソッドは、次のものを含むレスポンスの本文を返します。

  • messages[]: Message リソースの配列。
  • nextPageToken: 結果が複数ページにわたるリクエストの場合、後続の呼び出しで使用して、より多くのメッセージを一覧表示できるトークン。
  • resultSizeEstimate: 結果の推定合計数。

メッセージのコンテンツとメタデータをすべて取得するには、message.id フィールドを使用して users.messages.get メソッドを呼び出します。