Permissions error using UrlFetchApp in Gmail Add-on

The UrlFetchApp service requires an additional scope, https://www.googleapis.com/auth/script.external_request. Add it to your list of scopes and the code should work.

The scopes required for each Apps Script method is listed under the "Authorization" section in the reference docs (example). Alternatively, you can discover the scopes required by your script by temporarily removing the oauthScopes section of the manifest and viewing the auto-determined scopes for your code in File > Project properties > Scopes. (If you define any scopes in your manifest, this disables the "automatic scope detection" behavior of Apps Script.)

References

  • Setting Scopes
  • Manifest File
  • All Google Scopes

The accepted answer was from 2017. I don't know if Google has changed its authorization policy since then, but simply adding a new scope to the Project Properties settings won't work.

How do you trigger the function that call fetch?. You can't use simple triggers to do that. They fire automatically, so they can't access services that require authorization. UrlFetchApp definitely requires permission. There is no way to open a dialog to ask for users' content with simple triggers.

You, as the script owner, can add new authorization scope, but what happens when you deploy this script with end users? How are they going to grant their permission to the script to make API calls to some unfamiliar servers?

To get around this, you need to use installable triggers. Whatever are available in simple triggers, there are equivalent in installable triggers.

Let's assume that you want to call the API on opening the spreadsheet.

From the Script Editor, go to Edit >> Current Project's Triggers and set up a new trigger.

  • Under Run, select the name of the function that you want to trigger. In the OP's case, it's the getContextualAddOn(e) function.

  • Under Select event source, choose From spreadsheet.

  • Under Event type, choose On Open.

  • Configure other settings as you like and save.