google-apps-scriptgoogle-sheetsgoogle-drive-api

Adding message to email when using addEditor()


In Apps Script, I'm currently programmatically generating files, adding a user via addEditor() and sending them an email automatically.

What I'd like to do now is expand this to include a message. I think this corresponds with this box in green:

enter image description here

I've also found a similar question here, but have been unable to get it working: How to send a custom message when adding a viewer to Google Spreadsheet via Google Apps Scripts?

This is what I have so far:

  setPermission(documentId, email) {

    // Get the document to set permissions on
    const file = DriveApp.getFileById(documentId);

    // Turn off sharing by editors
    file.setShareableByEditors(false);

    // Add the email to editors
    file.addEditor(email);

  }  

If I try to do something like:

...
file.addEditor(email, {emailMessage: 'Test'});

I get the following error:

Exception: The parameters (String,(class)) don't match the method signature for DriveApp.File.addEditor.

So I'm curious if:

  1. Is this doable?
  2. And what does the syntax need to be?

Solution

  • As documented, file.addEditor() has only one argument: an email address (or a User object). So an email message cannot be added via that method.

    However, you can accomplish this using the Advanced Drive Service. First you'll need to enable the Advanced Drive Service.

    Then use something like this (reference):

    Drive.Permissions.insert(
      {
        'role': 'writer',
        'type': 'user',
        'value': email // the email address you wish to share with
      },
      documentId, // id of the file you want to share
      {
        'sendNotificationEmails': 'true',
        'emailMessage': message // The message you want to send, as a plain text string
      });