لیست پیام های Gmail، لیست پیام های Gmail

این صفحه نحوه فراخوانی متد users.messages.list Gmail API را توضیح می دهد.

این روش آرایه‌ای از منابع Message Gmail را برمی‌گرداند که حاوی id پیام و threadId است. برای بازیابی جزئیات کامل پیام، از روش users.messages.get استفاده کنید.

پیش نیازها

پایتون

یک پروژه Google Cloud با فعال کردن Gmail API. برای مراحل، Gmail API Python را تکمیل کنید.

لیست پیام ها

متد users.messages.list از چندین پارامتر پرس و جو برای فیلتر کردن پیام ها پشتیبانی می کند:

  • maxResults : حداکثر تعداد پیام برای بازگشت (به طور پیش فرض 100، حداکثر 500).
  • pageToken : رمزی برای بازیابی صفحه خاصی از نتایج.
  • q : رشته پرس و جو برای فیلتر کردن پیام ها، مانند from:someuser@example.com is:unread" .
  • labelIds : فقط پیام‌هایی را با برچسب‌هایی برمی‌گرداند که با همه شناسه‌های برچسب مشخص‌شده مطابقت دارند.
  • includeSpamTrash : پیام‌هایی از SPAM و TRASH را در نتایج قرار دهید.

نمونه کد

پایتون

نمونه کد زیر نحوه فهرست کردن پیام‌ها را برای کاربر تأیید شده 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()

متد users.messages.list بدنه پاسخی را برمی‌گرداند که حاوی موارد زیر است:

  • messages[] : آرایه ای از منابع Message .
  • nextPageToken : برای درخواست هایی با چندین صفحه از نتایج، رمزی است که می تواند همراه با تماس های بعدی برای فهرست کردن پیام های بیشتر استفاده شود.
  • resultSizeEstimate : تعداد کل تخمینی نتایج.

برای واکشی محتوای کامل پیام و فراداده، از فیلد message.id برای فراخوانی روش users.messages.get استفاده کنید.

،

این صفحه نحوه فراخوانی متد users.messages.list Gmail API را توضیح می دهد.

این روش آرایه‌ای از منابع Message Gmail را برمی‌گرداند که حاوی id پیام و threadId است. برای بازیابی جزئیات کامل پیام، از روش users.messages.get استفاده کنید.

پیش نیازها

پایتون

یک پروژه Google Cloud با فعال کردن Gmail API. برای مراحل، Gmail API Python را تکمیل کنید.

لیست پیام ها

متد users.messages.list از چندین پارامتر پرس و جو برای فیلتر کردن پیام ها پشتیبانی می کند:

  • maxResults : حداکثر تعداد پیام برای بازگشت (به طور پیش فرض 100، حداکثر 500).
  • pageToken : رمزی برای بازیابی صفحه خاصی از نتایج.
  • q : رشته پرس و جو برای فیلتر کردن پیام ها، مانند from:someuser@example.com is:unread" .
  • labelIds : فقط پیام‌هایی را با برچسب‌هایی برمی‌گرداند که با همه شناسه‌های برچسب مشخص‌شده مطابقت دارند.
  • includeSpamTrash : پیام‌هایی از SPAM و TRASH را در نتایج قرار دهید.

نمونه کد

پایتون

نمونه کد زیر نحوه فهرست کردن پیام‌ها را برای کاربر تأیید شده 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()

متد users.messages.list بدنه پاسخی را برمی‌گرداند که حاوی موارد زیر است:

  • messages[] : آرایه ای از منابع Message .
  • nextPageToken : برای درخواست هایی با چندین صفحه از نتایج، رمزی است که می تواند همراه با تماس های بعدی برای فهرست کردن پیام های بیشتر استفاده شود.
  • resultSizeEstimate : تعداد کل تخمینی نتایج.

برای واکشی محتوای کامل پیام و فراداده، از فیلد message.id برای فراخوانی روش users.messages.get استفاده کنید.