Search code examples
google-apps-scriptgmailgmail-addons

In Gmail Addons, how to get access to all threads' details returned by GmailApp.search?


With the following method, I get the error:

"Missing access token for authorization. Request: MailboxService.GetThread"

at the var button [...] line.

function createItemListCard() {
    var card = CardService.newCardBuilder().setHeader(CardService.newCardHeader().setTitle('Item list'));
    var section = CardService.newCardSection().setHeader("<b>Items</b>");
    var threads = GmailApp.search("some search query")
for (var i = 0; i < threads.length; i++) {
        var button = CardService.newTextButton().setText(threads[i].getFirstMessageSubject()).setOpenLink(CardService.newOpenLink().setUrl(threads[i].getPermalink()));
    }
    return card.build();
}

Example code snipplets seem to be using access tokens per message, like:

var accessToken = e.messageMetadata.accessToken;
GmailApp.setCurrentMessageAccessToken(accessToken);

But it does not help at all. Most likely due to accessing all threads not just a single message. The scope mentioned in docs for search is in place: https://mail.google.com/

There must be a way to access results of GmailApp.search in Gmail Addons. How to do it?


Solution

  • You will need to add

    https://www.googleapis.com/auth/gmail.readonly
    

    to the scopes in your manifest.

    What might not be obvious is that you'll need to REMOVE

    https://www.googleapis.com/auth/gmail.addons.current.message.readonly
    

    from the manifest. It appears that the apps script environment chooses the most restrictive set of permissions from the scopes available: if you have both scopes in your manifest you will only get the current.message.readonly permission (and you won't be able to interact with any other messages).

    I also found that I needed to completely uninstall the addon and then re-install it to get the new scopes to take effect.