Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Dịch vụ Gmail nâng cao cho phép bạn sử dụng API Gmail trong Apps Script. Tương tự như dịch vụ Gmail tích hợp của Apps Script, API này cho phép tập lệnh tìm và sửa đổi các chuỗi, thư và nhãn trong hộp thư Gmail. Trong hầu hết các trường hợp, dịch vụ tích hợp sẵn sẽ dễ sử dụng hơn, nhưng dịch vụ nâng cao này cung cấp thêm một số tính năng và quyền truy cập vào thông tin chi tiết hơn về nội dung trên Gmail.
Tài liệu tham khảo
Để biết thông tin chi tiết về dịch vụ này, hãy xem tài liệu tham khảo cho Gmail API.
Giống như tất cả các dịch vụ nâng cao trong Apps Script, dịch vụ Gmail nâng cao sử dụng cùng các đối tượng, phương thức và tham số như API công khai. Để biết thêm thông tin, hãy xem bài viết Cách xác định chữ ký phương thức.
/** * 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);}}
Liệt kê các đoạn trích trong hộp thư đến
Ví dụ sau đây minh hoạ cách liệt kê các đoạn văn bản được liên kết với từng chuỗi trong hộp thư đến của người dùng. Lưu ý việc sử dụng mã thông báo trang để truy cập vào danh sách đầy đủ các kết quả.
/** * 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);}}
Liệt kê nhật ký gần đây
Ví dụ sau đây minh hoạ cách ghi nhật ký nhật ký hoạt động gần đây.
Cụ thể, ví dụ này khôi phục mã bản ghi nhật ký được liên kết với tin nhắn gần đây nhất mà người dùng đã gửi, sau đó ghi lại mã tin nhắn của mọi tin nhắn đã thay đổi kể từ thời điểm đó. Mỗi thông báo thay đổi chỉ được ghi nhật ký một lần, bất kể có bao nhiêu sự kiện thay đổi trong bản ghi nhật ký. Lưu ý việc sử dụng mã thông báo trang để truy cập vào danh sách đầy đủ các kết quả.
/** * 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);}}
Liệt kê thông báo
Ví dụ sau đây minh hoạ cách liệt kê các thư chưa đọc của người dùng Gmail.
/** * 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,["Cập nhật lần gần đây nhất: 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```"]]