Koleksiyonlar ile düzeninizi koruyun
İçeriği tercihlerinize göre kaydedin ve kategorilere ayırın.
Gelişmiş Gmail hizmeti, Apps Komut Dosyası'nda Gmail API'yi kullanmanıza olanak tanır. Apps Komut Dosyası'nın yerleşik Gmail hizmetine benzer şekilde bu API, komut dosyalarının Gmail posta kutusundaki ileti dizilerini, iletileri ve etiketleri bulup değiştirmesine olanak tanır. Çoğu durumda, yerleşik hizmetin kullanımı daha kolaydır. Ancak bu gelişmiş hizmet, birkaç ek özellik ve Gmail içeriği hakkında daha ayrıntılı bilgilere erişim sağlar.
Referans
Bu hizmet hakkında ayrıntılı bilgi için Gmail API'nin referans dokümanlarına bakın.
Apps Komut Dosyası'ndaki tüm gelişmiş hizmetler gibi, gelişmiş Gmail hizmeti de herkese açık API ile aynı nesneleri, yöntemleri ve parametreleri kullanır. Daha fazla bilgi için Yöntem imzaları nasıl belirlenir? başlıklı makaleyi inceleyin.
Sorunları bildirmek ve diğer destek seçeneklerini öğrenmek için Gmail Destek Kılavuzu'na bakın.
Örnek kod
Aşağıdaki örnek kodda API'nin 1. sürümü kullanılmaktadır.
Etiket bilgilerini listeleme
Aşağıdaki örnekte, kullanıcının tüm etiket bilgilerinin nasıl listeleneceği gösterilmektedir.
Etiket adı, türü, kimliği ve görünürlük ayarları buna dahildir.
/** * Lists the user's labels, including name, type, * ID and visibility information. */functionlistLabelInfo(){try{constresponse=Gmail.Users.Labels.list('me');for(leti=0;i < response.labels.length;i++){constlabel=response.labels[i];console.log(JSON.stringify(label));}}catch(err){console.log(err);}}
Gelen kutusu snippet'lerini listeleme
Aşağıdaki örnekte, kullanıcının gelen kutusundaki her ileti dizisiyle ilişkili metin snippet'lerinin nasıl listeleneceği gösterilmektedir. Sonuçların tam listesine erişmek için sayfa jetonlarının kullanıldığına dikkat edin.
/** * Lists, for each thread in the user's Inbox, a * snippet associated with that thread. */functionlistInboxSnippets(){try{letpageToken;do{constthreadList=Gmail.Users.Threads.list('me',{q:'label:inbox',pageToken:pageToken});if(threadList.threads && threadList.threads.length > 0){threadList.threads.forEach(function(thread){console.log('Snippet: %s',thread.snippet);});}pageToken=threadList.nextPageToken;}while(pageToken);}catch(err){console.log(err);}}
Son geçmişi listeleme
Aşağıdaki örnekte, son etkinlik geçmişinin nasıl kaydedileceği gösterilmektedir.
Bu örnekte, kullanıcının en son gönderdiği iletiyle ilişkili geçmiş kaydı kimliği kurtarılır ve ardından o zamandan beri değişen tüm iletilerin ileti kimlikleri kaydedilir. Geçmiş kayıtlarında kaç değişiklik etkinliği olursa olsun, değiştirilen her ileti yalnızca bir kez günlüğe kaydedilir. Sonuçların tam listesine erişmek için sayfa jetonlarının kullanıldığına dikkat edin.
/** * Gets a history record ID associated with the most * recently sent message, then logs all the message IDs * that have changed since that message was sent. */functionlogRecentHistory(){try{// Get the history ID associated with the most recent// sent message.constsent=Gmail.Users.Threads.list('me',{q:'label:sent',maxResults:1});if(!sent.threads||!sent.threads[0]){console.log('No sent threads found.');return;}consthistoryId=sent.threads[0].historyId;// Log the ID of each message changed since the most// recent message was sent.letpageToken;constchanged=[];do{constrecordList=Gmail.Users.History.list('me',{startHistoryId:historyId,pageToken:pageToken});consthistory=recordList.history;if(history && history.length > 0){history.forEach(function(record){record.messages.forEach(function(message){if(changed.indexOf(message.id)===-1){changed.push(message.id);}});});}pageToken=recordList.nextPageToken;}while(pageToken);changed.forEach(function(id){console.log('Message Changed: %s',id);});}catch(err){console.log(err);}}
Mesajları listeleme
Aşağıdaki örnekte, Gmail kullanıcısının okunmamış iletilerinin nasıl listeleneceği gösterilmektedir.
/** * Lists unread messages in the user's inbox using the advanced Gmail service. */functionlistMessages(){// The special value 'me' indicates the authenticated user.constuserId='me';// Define optional parameters for the request.constoptions={maxResults:10,// Limit the number of messages returned.q:'is:unread',// Search for unread messages.};try{// Call the Gmail.Users.Messages.list method.constresponse=Gmail.Users.Messages.list(userId,options);constmessages=response.messages;console.log('Unread Messages:');for(constmessageofmessages){console.log(`- Message ID: ${message.id}`);}}catch(err){// Log any errors to the Apps Script execution log.console.log(`Failed with error: ${err.message}`);}}
[null,null,["Son güncelleme tarihi: 2025-08-31 UTC."],[[["\u003cp\u003eThe Advanced Gmail service in Apps Script lets you use the Gmail API to interact with your mailbox, offering more features than the built-in service.\u003c/p\u003e\n"],["\u003cp\u003eThis advanced service requires enabling before use and provides access to detailed information about threads, messages, and labels.\u003c/p\u003e\n"],["\u003cp\u003eYou can utilize the provided sample code snippets to list label information, inbox snippets, and recent history within your Gmail account.\u003c/p\u003e\n"],["\u003cp\u003eThe Gmail API might limit data returned in list requests for performance, requiring follow-up 'get' requests for detailed information.\u003c/p\u003e\n"],["\u003cp\u003eFor comprehensive details, refer to the reference documentation, support guide, and sample code on GitHub.\u003c/p\u003e\n"]]],[],null,["# Advanced Gmail Service\n\nThe Advanced Gmail service allows you to use the [Gmail API](/gmail/api) in\nApps Script. Much like Apps Script's [built-in Gmail service](/apps-script/reference/gmail),\nthis API allows scripts to find and modify threads, messages, and labels in a\nGmail mailbox. In most cases, the built-in service is easier to use, but this\nadvanced service provides a few extra features and access to more detailed\ninformation about Gmail content.\n| **Note:** This is an advanced service that must be [enabled before use](/apps-script/guides/services/advanced).\n\nReference\n---------\n\nFor detailed information on this service, see the\n[reference documentation](/gmail/api/v1/reference) for the Gmail API.\nLike all advanced services in Apps Script, the advanced Gmail service uses the\nsame objects, methods, and parameters as the public API. For more information, see [How method signatures are determined](/apps-script/guides/services/advanced#how_method_signatures_are_determined).\n| **Note:** To improve performance, the Gmail API often restricts the amount of information returned from `list` requests to thread, message or label IDs and other simple information. More detailed information about a particular thread, message or label can be obtained by issuing a follow-up `get` request using the associated ID.\n\nTo report issues and find other support, see the\n[Gmail support guide](/gmail/api/support).\n\nSample code\n-----------\n\nThe sample code below uses [version 1](/gmail/api/v1/reference) of the API.\n\n### List label information\n\nThe following example demonstrates how to list all the user's label information.\nThis includes the label name, type, ID and visibility settings. \nadvanced/gmail.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/gmail.gs) \n\n```javascript\n/**\n * Lists the user's labels, including name, type,\n * ID and visibility information.\n */\nfunction listLabelInfo() {\n try {\n const response =\n Gmail.Users.Labels.list('me');\n for (let i = 0; i \u003c response.labels.length; i++) {\n const label = response.labels[i];\n console.log(JSON.stringify(label));\n }\n } catch (err) {\n console.log(err);\n }\n}\n```\n\n### List inbox snippets\n\nThe following example demonstrates how to list text snippets associated with\neach thread in the user's Inbox. Notice the use of page tokens to access the\nfull list of results. \nadvanced/gmail.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/gmail.gs) \n\n```javascript\n/**\n * Lists, for each thread in the user's Inbox, a\n * snippet associated with that thread.\n */\nfunction listInboxSnippets() {\n try {\n let pageToken;\n do {\n const threadList = Gmail.Users.Threads.list('me', {\n q: 'label:inbox',\n pageToken: pageToken\n });\n if (threadList.threads && threadList.threads.length \u003e 0) {\n threadList.threads.forEach(function (thread) {\n console.log('Snippet: %s', thread.snippet);\n });\n }\n pageToken = threadList.nextPageToken;\n } while (pageToken);\n } catch (err) {\n console.log(err);\n }\n}\n```\n\n### List recent history\n\nThe following example demonstrates how to log recent activity history.\nSpecifically, this example recovers the history record ID associated with the\nuser's most recently sent message, and then logs the message IDs of every\nmessage that has changed since that time. Each changed message is only logged\nonce, no matter how many change events are in the history records. Notice the\nuse of page tokens to access the full list of results. \nadvanced/gmail.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/gmail.gs) \n\n```javascript\n/**\n * Gets a history record ID associated with the most\n * recently sent message, then logs all the message IDs\n * that have changed since that message was sent.\n */\nfunction logRecentHistory() {\n try {\n // Get the history ID associated with the most recent\n // sent message.\n const sent = Gmail.Users.Threads.list('me', {\n q: 'label:sent',\n maxResults: 1\n });\n if (!sent.threads || !sent.threads[0]) {\n console.log('No sent threads found.');\n return;\n }\n const historyId = sent.threads[0].historyId;\n\n // Log the ID of each message changed since the most\n // recent message was sent.\n let pageToken;\n const changed = [];\n do {\n const recordList = Gmail.Users.History.list('me', {\n startHistoryId: historyId,\n pageToken: pageToken\n });\n const history = recordList.history;\n if (history && history.length \u003e 0) {\n history.forEach(function (record) {\n record.messages.forEach(function (message) {\n if (changed.indexOf(message.id) === -1) {\n changed.push(message.id);\n }\n });\n });\n }\n pageToken = recordList.nextPageToken;\n } while (pageToken);\n\n changed.forEach(function (id) {\n console.log('Message Changed: %s', id);\n });\n } catch (err) {\n console.log(err);\n }\n}\n```\n\n### List messages\n\nThe following example demonstrates how to list the Gmail user's\nunread messages. \nadvanced/gmail.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/gmail.gs) \n\n```javascript\n/**\n * Lists unread messages in the user's inbox using the advanced Gmail service.\n */\nfunction listMessages() {\n // The special value 'me' indicates the authenticated user.\n const userId = 'me';\n\n // Define optional parameters for the request.\n const options = {\n maxResults: 10, // Limit the number of messages returned.\n q: 'is:unread', // Search for unread messages.\n };\n\n try {\n // Call the Gmail.Users.Messages.list method.\n const response = Gmail.Users.Messages.list(userId, options);\n const messages = response.messages;\n console.log('Unread Messages:');\n\n for (const message of messages) {\n console.log(`- Message ID: ${message.id}`);\n }\n } catch (err) {\n // Log any errors to the Apps Script execution log.\n console.log(`Failed with error: ${err.message}`);\n }\n}\n```"]]