רשימת הודעות Gmail

במאמר הזה מוסבר איך לקרוא לשיטה messages.list של Gmail API.

השיטה מחזירה מערך של אובייקטים של Gmail messages שמכילים את ההודעה id ואת threadId. כדי לאחזר את הפרטים המלאים של ההודעה, משתמשים בשיטה messages.get.

אובייקטים messages שמוחזרים מופיעים בסדר כרונולוגי הפוך (מהחדש לישן).

דרישות מוקדמות

Python

פרויקט ב-Google Cloud שבו מופעל Gmail API. הוראות מפורטות זמינות במאמר בנושא Gmail API Python quickstart.

הצגת הודעות ברשימה

השיטה 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.