Search code examples
google-apps-scriptgoogle-docsgoogle-formsgoogle-workspace

Adding editor with script throws 'Invalid email' and stops script


I'm using Apps Script to generate a document including responses from a Google form and store this in a new folder. I also enable the user submitting the form editor access based on the email they provide.

.addEditor(email);

This seems to work for Google domains or company domains using g-suite.

When the email is not Google based however, the script breaks.

'Invalid email: [email protected]'

Looking for a means of skipping past this error and having the script complete.

  function autoFillGoogleDocFromForm(e) {
  var Timestamp = e.values[0];
  var email = e.values[1];

  var file = DriveApp.getFileById('FILEID');
  var folder = createfolder(); 
  var copy = file.makeCopy(Name + ' - Document', folder); 
  var newId = copy.getId();
  var doc = DocumentApp.openById(newId).addEditor(email);
  
  var body = doc.getBody();
  body.replaceText('{{Timestamp}}', Timestamp); 
  body.replaceText('{{Email}}', Email);  
  doc.saveAndClose();                                             


}

Solution

  • Looking for a means of skipping past this error and having the script complete.

    If you are looking for a solution to skip the error, then you can always use try...catch:

      function autoFillGoogleDocFromForm(e) {
      var Timestamp = e.values[0];
      var email = e.values[1];
    
      var file = DriveApp.getFileById('FILEID');
      var folder = createfolder(); 
      var copy = file.makeCopy(Name + ' - Document', folder); 
      var newId = copy.getId();
      
      try{
      var doc = DocumentApp.openById(newId).addEditor(email);
      }
      catch(error){
      var doc = DocumentApp.openById(newId);
      }
      
      var body = doc.getBody();
      body.replaceText('{{Timestamp}}', Timestamp); 
      body.replaceText('{{Email}}', Email);  
      doc.saveAndClose();                                             
      
    }
    

    This snippet will try to execute var doc = DocumentApp.openById(newId).addEditor(email);.

    If the latter fails, then it will just open the document var doc = DocumentApp.openById(newId); and continue with the rest of the code.