Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
El servicio avanzado de Gmail te permite usar la API de Gmail en Apps Script. Al igual que el servicio integrado de Gmail de Apps Script, esta API permite que las secuencias de comandos encuentren y modifiquen hilos, mensajes y etiquetas en un buzón de Gmail. En la mayoría de los casos, el servicio integrado es más fácil de usar, pero este servicio avanzado proporciona algunas funciones adicionales y acceso a información más detallada sobre el contenido de Gmail.
Referencia
Para obtener información detallada sobre este servicio, consulta la documentación de referencia de la API de Gmail.
Al igual que todos los servicios avanzados de Apps Script, el servicio avanzado de Gmail usa los mismos objetos, métodos y parámetros que la API pública. Para obtener más información, consulta Cómo se determinan las firmas de métodos.
El siguiente código de ejemplo usa la versión 1 de la API.
Cómo enumerar la información de la etiqueta
En el siguiente ejemplo, se muestra cómo enumerar toda la información de las etiquetas del usuario.
Esto incluye el nombre, el tipo, el ID y la configuración de visibilidad de la etiqueta.
/** * 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);}}
Enumera fragmentos de Recibidos
En el siguiente ejemplo, se muestra cómo enumerar los fragmentos de texto asociados a cada conversación del buzón de entrada del usuario. Observa el uso de tokens de página para acceder a la 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);}}
Cómo ver el historial reciente
En el siguiente ejemplo, se muestra cómo registrar el historial de actividad reciente.
Específicamente, este ejemplo recupera el ID del registro de historial asociado con el mensaje enviado más recientemente por el usuario y, luego, registra los IDs de todos los mensajes que cambiaron desde ese momento. Cada mensaje modificado se registra solo una vez, sin importar cuántos eventos de cambio haya en los registros del historial. Observa el uso de tokens de página para acceder a la 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);}}
Mostrar mensajes
En el siguiente ejemplo, se muestra cómo enumerar los mensajes no leídos del usuario de 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 actualización: 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```"]]