แสดงข้อความ Gmail

เอกสารนี้อธิบายวิธีเรียกใช้เมธอด messages.list ของ Gmail API

เมธอดจะแสดงผลอาร์เรย์ของออบเจ็กต์ messages ของ Gmail ซึ่งมีidและthreadIdของข้อความ หากต้องการดึงรายละเอียดข้อความทั้งหมด ให้ใช้เมธอด messages.get

ข้อกำหนดเบื้องต้น

Python

โปรเจ็กต์ Google Cloud ที่เปิดใช้ Gmail API ดูขั้นตอนได้ที่คู่มือเริ่มใช้งานฉบับย่อของ Gmail API Python

แสดงรายการข้อความ

messages.list เมธอดรองรับพารามิเตอร์การค้นหาหลายรายการเพื่อกรองข้อความ

  • maxResults: จำนวนข้อความสูงสุดที่จะแสดงผล (ค่าเริ่มต้นคือ 100 และสูงสุดคือ 500)
  • pageToken: โทเค็นเพื่อดึงผลลัพธ์หน้าใดหน้าหนึ่ง
  • q: สตริงการค้นหาเพื่อกรองข้อความ เช่น from:someuser@example.com is:unread
  • labelIds: แสดงเฉพาะข้อความที่มีป้ายกำกับที่ตรงกับรหัสป้ายกำกับ ที่ระบุทั้งหมด
  • includeSpamTrash: รวมข้อความจาก SPAM และ TRASH ไว้ในผลการค้นหา

ตัวอย่างโค้ด

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

เมธอด messages.list จะแสดงเนื้อหาการตอบกลับที่มีข้อมูลต่อไปนี้

  • messages[]: อาร์เรย์ของทรัพยากร Message
  • nextPageToken: สำหรับคำขอที่มีผลลัพธ์หลายหน้า โทเค็นที่ใช้กับการเรียกครั้งถัดไปเพื่อแสดงข้อความเพิ่มเติมได้
  • resultSizeEstimate: จำนวนผลการค้นหาทั้งหมดโดยประมาณ

หากต้องการดึงเนื้อหาและข้อมูลเมตาของข้อความทั้งหมด ให้ใช้ฟิลด์ message.id เพื่อเรียกใช้เมธอด messages.get