Koleksiyonlar ile düzeninizi koruyun
İçeriği tercihlerinize göre kaydedin ve kategorilere ayırın.
Bu sayfada, Gmail API'nin users.messages.list yönteminin nasıl çağrılacağı açıklanmaktadır.
Bu yöntem, ileti id ve threadId içeren bir Gmail Message kaynakları dizisi döndürür. Tam mesaj ayrıntılarını almak için users.messages.get yöntemini kullanın.
users.messages.list yöntemi, iletileri filtrelemek için çeşitli sorgu parametrelerini destekler:
maxResults: Döndürülecek maksimum ileti sayısı (varsayılan olarak 100, maksimum 500).
pageToken: Sonuçların belirli bir sayfasını almak için kullanılan jeton.
q: Mesajları filtrelemek için kullanılan sorgu dizesi (ör. from:someuser@example.com is:unread").
labelIds: Yalnızca belirtilen tüm etiket kimlikleriyle eşleşen etiketlere sahip iletileri döndürür.
includeSpamTrash: SPAM ve TRASH adreslerinden gelen iletileri sonuçlara dahil edin.
Kod örneği
Python
Aşağıdaki kod örneğinde, kimliği doğrulanmış Gmail kullanıcısının iletilerinin nasıl listeleneceği gösterilmektedir. Kod, sorguyla eşleşen tüm iletileri almak için sayfalara ayırma işlemini gerçekleştirir.
importos.pathfromgoogle.auth.transport.requestsimportRequestfromgoogle.oauth2.credentialsimportCredentialsfromgoogle_auth_oauthlib.flowimportInstalledAppFlowfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpError# If modifying these scopes, delete the file token.json.SCOPES=["https://www.googleapis.com/auth/gmail.readonly"]defmain():"""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.ifos.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.ifnotcredsornotcreds.valid:ifcredsandcreds.expiredandcreds.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 runwithopen("token.json","w")astoken:token.write(creds.to_json())try:# Call the Gmail APIservice=build("gmail","v1",credentials=creds)results=(service.users().messages().list(userId="me",labelIds=["INBOX"]).execute())messages=results.get("messages",[])ifnotmessages:print("No messages found.")returnprint("Messages:")formessageinmessages:print(f'Message ID: {message["id"]}')msg=(service.users().messages().get(userId="me",id=message["id"]).execute())print(f' Subject: {msg["snippet"]}')exceptHttpErroraserror:# TODO(developer) - Handle errors from gmail API.print(f"An error occurred: {error}")if__name__=="__main__":main()
users.messages.list yöntemi, aşağıdakileri içeren bir yanıt gövdesi döndürür:
messages[]: Message kaynaklarının dizisi.
nextPageToken: Birden fazla sonuç sayfası içeren istekler için, daha fazla mesajı listelemek üzere sonraki çağrılarda kullanılabilecek bir jeton.
resultSizeEstimate: Tahmini toplam sonuç sayısı.
İletinin tam içeriğini ve meta verilerini getirmek için message.id alanını kullanarak users.messages.get yöntemini çağırın.
[[["Anlaması kolay","easyToUnderstand","thumb-up"],["Sorunumu çözdü","solvedMyProblem","thumb-up"],["Diğer","otherUp","thumb-up"]],[["İhtiyacım olan bilgiler yok","missingTheInformationINeed","thumb-down"],["Çok karmaşık / çok fazla adım var","tooComplicatedTooManySteps","thumb-down"],["Güncel değil","outOfDate","thumb-down"],["Çeviri sorunu","translationIssue","thumb-down"],["Örnek veya kod sorunu","samplesCodeIssue","thumb-down"],["Diğer","otherDown","thumb-down"]],["Son güncelleme tarihi: 2025-08-01 UTC."],[],[],null,["# List Gmail messages\n\nThis page explains how to call the Gmail API's\n[`users.messages.list`](/workspace/gmail/api/reference/rest/v1/users.messages/list)\nmethod.\n\nThe method returns an array of Gmail `Message` resources that\ncontain the message `id` and `threadId`. To retrieve full message details, use\nthe\n[`users.messages.get`](/workspace/gmail/api/reference/rest/v1/users.messages/get)\nmethod.\n\nPrerequisites\n-------------\n\n### Python\n\nA Google Cloud project with the Gmail API enabled. For steps, complete\nthe\n[Gmail API Python quickstart](/workspace/gmail/api/quickstart/python).\n\nList messages\n-------------\n\nThe `users.messages.list` method supports several query parameters to filter the\nmessages:\n\n- `maxResults`: Maximum number of messages to return (defaults to 100, max 500).\n- `pageToken`: Token to retrieve a specific page of results.\n- `q`: Query string to filter messages, such as `from:someuser@example.com is:unread\"`.\n- `labelIds`: Only return messages with labels that match all specified label IDs.\n- `includeSpamTrash`: Include messages from `SPAM` and `TRASH` in the results.\n\n### Code sample\n\n### Python\n\nThe following code sample shows how to list messages for the authenticated\nGmail user. The code handles pagination to retrieve all\nmessages matching the query. \ngmail/snippet/list_messages.py \n[View on GitHub](https://github.com/googleworkspace/python-samples/blob/main/gmail/snippet/list_messages.py) \n\n```python\nimport os.path\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\n# If modifying these scopes, delete the file token.json.\nSCOPES = [\"https://www.googleapis.com/auth/gmail.readonly\"]\n\n\ndef main():\n \"\"\"Shows basic usage of the Gmail API.\n Lists the user's Gmail messages.\n \"\"\"\n creds = None\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists(\"token.json\"):\n creds = Credentials.from_authorized_user_file(\"token.json\", SCOPES)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\"credentials.json\", SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open(\"token.json\", \"w\") as token:\n token.write(creds.to_json())\n\n try:\n # Call the Gmail API\n service = build(\"gmail\", \"v1\", credentials=creds)\n results = (\n service.users().messages().list(userId=\"me\", labelIds=[\"INBOX\"]).execute()\n )\n messages = results.get(\"messages\", [])\n\n if not messages:\n print(\"No messages found.\")\n return\n\n print(\"Messages:\")\n for message in messages:\n print(f'Message ID: {message[\"id\"]}')\n msg = (\n service.users().messages().get(userId=\"me\", id=message[\"id\"]).execute()\n )\n print(f' Subject: {msg[\"snippet\"]}')\n\n except HttpError as error:\n # TODO(developer) - Handle errors from gmail API.\n print(f\"An error occurred: {error}\")\n\n\nif __name__ == \"__main__\":\n main()\n```\n\nThe `users.messages.list` method returns a response body that contains the\nfollowing:\n\n- `messages[]`: An array of `Message` resources.\n- `nextPageToken`: For requests with multiple pages of results, a token that can be used with a subsequent calls to list more messages.\n- `resultSizeEstimate`: An estimated total number of results.\n\nTo fetch the full message content and metadata, use the `message.id` field to\ncall the\n[`users.messages.get`](/workspace/gmail/api/reference/rest/v1/users.messages/get)\nmethod.\n\nRelated resources\n-----------------\n\n- [`users.messages.list`](/workspace/gmail/api/reference/rest/v1/users.messages/list)\n- [`users.messages.get`](/workspace/gmail/api/reference/rest/v1/users.messages/get)"]]