Liệt kê thư trên Gmail

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

Phương thức này trả về một mảng các đối tượng messages 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 messages.get.

Các đối tượng messages được trả về sẽ xuất hiện theo thứ tự thời gian đảo ngược (mới nhất xếp trước).

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

Python

Một dự án trên đám mây của Google Cloud đã bật API Gmail. Để xem các bước, hãy hoàn tất hướng dẫn nhanh về API Gmail bằng Python.

Liệt kê thông báo

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

  • maxResults: Số lượng thông báo tối đa 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 trùng khớp với tất cả mã nhận dạng nhãn đã chỉ định.
  • includeSpamTrash: Kết quả bao gồm thư từ 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 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 nội dung và siêu dữ liệu đầy đủ của thông báo, hãy sử dụng trường message.id để gọi phương thức messages.get.