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.

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

Python

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

Liệt kê tin nhắn

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 khớp với tất cả mã nhận dạng nhãn đã chỉ định.
  • includeSpamTrash: Thêm thư của SPAMTRASH vào kết quả.

Mã mẫu

Python

Mã mẫu sau đây cho biết 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 thông tin 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ể 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 messages.get.