Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
O serviço avançado do Gmail permite usar a API Gmail no Apps Script. Assim como o serviço integrado do Gmail do Apps Script,
essa API permite que os scripts encontrem e modifiquem conversas, mensagens e rótulos em uma
caixa de correio do Gmail. Na maioria dos casos, o serviço integrado é mais fácil de usar, mas esse serviço avançado oferece alguns recursos extras e acesso a informações mais detalhadas sobre o conteúdo do Gmail.
Referência
Para informações detalhadas sobre esse serviço, consulte a
documentação de referência da API Gmail.
Assim como todos os serviços avançados no Apps Script, o serviço avançado do Gmail usa os mesmos objetos, métodos e parâmetros que a API pública. Para mais informações, consulte Como as assinaturas de método são determinadas.
Para denunciar problemas e encontrar outras opções de suporte, consulte o
guia de suporte do Gmail.
O exemplo a seguir mostra como listar todas as informações de rótulo do usuário.
Isso inclui o nome, o tipo, o ID e as configurações de visibilidade do rótulo.
/** * 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);}}
Listar snippets da caixa de entrada
O exemplo a seguir demonstra como listar trechos de texto associados a
cada conversa na caixa de entrada do usuário. Observe o uso de tokens de página para acessar a
lista completa de resultados.
/** * 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);}}
Listar histórico recente
O exemplo a seguir mostra como registrar o histórico de atividades recentes.
Especificamente, este exemplo recupera o ID do registro de histórico associado à
mensagem enviada mais recentemente pelo usuário e registra os IDs de todas as
mensagens que mudaram desde então. Cada mensagem alterada é registrada apenas uma vez, não importa quantos eventos de mudança estejam nos registros do histórico. Observe o uso de tokens de página para acessar a lista completa de resultados.
/** * 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);}}
Listar mensagens
O exemplo a seguir mostra como listar as mensagens não lidas do usuário do 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,["Última atualização 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```"]]