Search code examples
javascriptgoogle-apps-scriptgoogle-cloud-platformgmailadd-on

Give permission in a gmail addon


I'm trying to put together a script for Gmail in Google Apps Scripts add-on that will reply to all email on weekends with an out of office message:

function autoReply() {
  var interval = 5;        //  if the script runs every 5 minutes; change otherwise
  var daysOff = [5];   // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
  var date = new Date();
  var day = date.getDay();
  var label = GmailApp.getUserLabelByName("autoresponded");
  if (daysOff.indexOf(day) > -1) {
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('is:inbox !label:autoresponded after:' + timeFrom);
    for (var i = 0; i < threads.length; i++) {
      var message = threads[i].getMessages()[0];
      if (message.getFrom().indexOf("[email protected]") < 0 && message.getFrom().indexOf("no-repl") < 0 && message.getFrom().indexOf("bounce") < 0 && message.getFrom().indexOf("spam") < 0) {
        threads[i].reply("", {
          htmlBody: "<p>Thank you for your message. We will get back to you as soon as possible. </p>"
        });
        label.addToThread(threads[i]);
      }
    }
  }
}

I keep getting this error however:

Exception: The script does not have permission to perform that action. Required permissions: (https://www.googleapis.com/auth/gmail.labels || https://www.googleapis.com/auth/gmail.metadata || https://www.googleapis.com/auth/gmail.readonly || https://www.googleapis.com/auth/gmail.modify || https://mail.google.com/)

This happened after I allowed permission in Gmail for my Gmail account. Is there something I'm missing here? Another layer that this is going through?

I tried deleting the add-on and re-allowing permissions for Gmail but no luck. The trigger for the add-on is every 5 mins just like the interval in the script. I tried going to the links in the errors but they just came up with blank pages.


Solution

  • You have to set the OAuth scopes in the Google Apps Script project manifest.


    From https://developers.google.com/workspace/add-ons/how-tos/building-gsuite-addons#verify_the_add-on_oauth_scopes

    Verify the add-on OAuth scopes
    Scopes define what actions the add-on is allowed to take on a user's behalf. It's a best practice for add-ons to only have scopes for actions they must have in order function and nothing more.

    In add-on projects, explicitly set the add-on scopes in order to ensure the add-on uses the least-permissive set of scopes possible. You define what scopes your add-on uses in the add-on manifest.

    See Scopes for more details.