Liệt kê thư trên Gmail

Trang này giải thích cách gọi phương thức users.messages.list của Gmail API.

Phương thức này trả về một mảng gồm các tài nguyên Message của Gmail chứa idthreadId của thư. Để truy xuất thông tin chi tiết đầy đủ về thông báo, hãy sử dụng phương thức users.messages.get.

Điều kiện tiên quyết

Python

Một dự án Google Cloud đã bật Gmail API. Để hoàn tất các bước, hãy hoàn thành hướng dẫn bắt đầu nhanh về Gmail API bằng Python.

Liệt kê thông báo

Phương thức users.messages.list hỗ trợ một số tham số truy vấn để lọc các thông báo:

  • maxResults: Số lượng tối đa thư cần trả về (mặc định là 100, tối đa là 500).
  • pageToken: Mã thông báo để truy xuất một trang kết quả cụ thể.
  • q: Chuỗi truy vấn để lọc thông báo, chẳng hạn như from:someuser@example.com is:unread".
  • labelIds: Chỉ trả về những thư có nhãn khớp với tất cả mã nhận dạng nhãn đã chỉ định.
  • includeSpamTrash: Kết quả bao gồm thư của SPAMTRASH.

Mã mẫu

Python

Mẫu mã sau đây cho thấy cách liệt kê thư cho người dùng Gmail đã xác thực. Mã này xử lý việc phân trang để truy xuất tất cả các thông báo khớp với truy vấn.

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

Phương thức users.messages.list trả về một nội dung phản hồi chứa những nội dung sau:

  • messages[]: Một mảng gồm các tài nguyên Message.
  • nextPageToken: Đối với các yêu cầu có nhiều trang kết quả, mã thông báo này có thể được dùng với các lệnh gọi tiếp theo để liệt kê thêm tin nhắn.
  • resultSizeEstimate: Tổng số kết quả ước tính.

Để tìm nạp toàn bộ nội dung và siêu dữ liệu của thông báo, hãy sử dụng trường message.id để gọi phương thức users.messages.get.