Search code examples
javascriptgmail-addons

How to use access tokens for Gmail apps?


I am trying to create a Gmail add-on scope access token, my current goal is to somehow get the selected message's attachments and content in Spreadsheets.

function onGmailDo(e) {
  var sheet = SpreadsheetApp.openByUrl(
    "https://docs.google.com/spreadsheets/d/14qsqQqHWQyVdbK-0LyBSac6eNqVZB1C0QxjE4xeBK_o/edit#gid=0"
  );

  var accessToken = e.messageMetadata.accessToken;
  var messageId = e.messageMetadata.messageId;
  GmailApp.setCurrentMessageAccessToken(accessToken);
  var mailMessage = GmailApp.getMessageById(messageId);

  var threads = GmailApp.getInboxThreads(0, 100);

  var attachmentDetails = [];
  var attachments = mailMessage.getAttachments();

  for (var k = 0; k < attachments.length; k++) {
    attachmentDetails.push(
      "${attachments[k].getName()} :${attachments[k].getSize()}"
    );
  }
  sheet.appendRow([
    mailMessage.getSubject(),
    mailMessage.getDate(),
    mailMessage.getFrom(),
    attachmentDetails.join("\n"),
  ]);
}

Solution

  • Some helpful services were missing. Also I had to include the following scopes in my manifest file for authorization purposes. Scopes: "https://mail.google.com/", "https://www.googleapis.com/auth/spreadsheets" Corrected code:

    function onGmailDo(e) {
      console.log(e);
      var text = e.parameters.text;
      var isHomepage = e.parameters.isHomepage === 'true';
      var card = createCard(text, isHomepage);
      var navigation = CardService.newNavigation()
          .updateCard(card);
      var actionResponse = CardService.newActionResponseBuilder()
          .setNavigation(navigation);
          var sheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/14qsqQqHWQyVdbK-0LyBSac6eNqVZB1C0QxjE4xeBK_o/edit#gid=0');
    
      var accessToken = e.messageMetadata.accessToken;
      var messageId = e.messageMetadata.messageId;
      GmailApp.setCurrentMessageAccessToken(accessToken);
      var mailMessage = GmailApp.getMessageById(messageId);
    
    
      var attachmentDetails = [];
      var attachments = mailMessage.getAttachments();
      
        for (var k = 0; k < attachments.length; k++) {
        
           attachmentDetails.push(attachments[k].getName());
           attachmentDetails.push(attachments[k].getSize());
        }
        sheet.appendRow([mailMessage.getSubject(), mailMessage.getDate(), mailMessage.getFrom(), attachmentDetails.join('\n')]);
        
      return actionResponse.build();
    }