列出 Gmail 郵件

本頁說明如何呼叫 Gmail API 的 users.messages.list 方法。

這個方法會傳回 Gmail Message 資源陣列,其中包含郵件 idthreadId。如要擷取完整的訊息詳細資料,請使用 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 方法。