عرض قائمة برسائل 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 طريقة.