고급 Gmail 서비스를 사용하면 Apps Script에서 Gmail API를 사용할 수 있습니다. Apps Script의 내장 Gmail 서비스와 마찬가지로 이 API를 사용하면 스크립트가 Gmail 메일함에서 스레드, 메시지, 라벨을 찾아 수정할 수 있습니다. 대부분의 경우 내장 서비스를 사용하는 것이 더 쉽지만 이 고급 서비스는 몇 가지 추가 기능과 Gmail 콘텐츠에 관한 더 자세한 정보에 대한 액세스를 제공합니다.
참조
이 서비스에 관한 자세한 내용은 Gmail API의 참조 문서를 참고하세요.
Apps Script의 모든 고급 서비스와 마찬가지로 고급 Gmail 서비스는 공개 API와 동일한 객체, 메서드, 매개변수를 사용합니다. 자세한 내용은 메서드 서명이 결정되는 방식을 참고하세요.
/** * 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);}}
받은편지함 스니펫 나열
다음 예에서는 사용자 받은편지함의 각 스레드와 연결된 텍스트 스니펫을 나열하는 방법을 보여줍니다. 결과의 전체 목록에 액세스하기 위해 페이지 토큰이 사용됩니다.
/** * 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);}}
최근 기록 나열
다음 예시는 최근 활동 기록을 로깅하는 방법을 보여줍니다.
특히 이 예에서는 사용자가 가장 최근에 보낸 메시지와 연결된 기록 레코드 ID를 복구한 다음 그 이후로 변경된 모든 메시지의 메시지 ID를 로깅합니다. 변경된 각 메시지는 기록 레코드에 변경 이벤트가 몇 개나 있는지와 관계없이 한 번만 로깅됩니다. 결과의 전체 목록에 액세스하기 위해 페이지 토큰을 사용하는 것을 확인하세요.
/** * 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);}}
/** * 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,["최종 업데이트: 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```"]]