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

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

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

ออบเจ็กต์ messages ที่แสดงผลจะแสดงตามลำดับเวลาแบบย้อนกลับ (ใหม่สุดก่อน)

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

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 เมธอด