Any way to share google docs programmatically?

2019-04-13 06:04发布

问题:

I have a program that will get data from a fusion table, put it in a google doc(using a template I made), make it a pdf and then display a link to it(to the pdf). My problem is that it works fine for my account but if anyone else tries to click on it they keep getting the "404 Not Found" error. My guess is that the error shows up because I am the only one allowed to view the file. My question is: Is there a way to programmatically share the file with everyone in the organization or is there another way to do it?

回答1:

You can do it using DocsList.addViewers(viewersEmails[])

here is an example that takes a list of viewers as parameter, add them as viewers and sends an email with the link :

function addviewers(viewers) { // pass emails as a string in CSV
  var viewerssArray = viewers.replace(/, /g,",").split(",");// the 'replace' is there to remove any spaces that could be in the string
  Logger.log(viewersArray.length+'  :  '+viewersArray);
  var file = DocsList.getFileById('your doc ID').addViewers(viewersArray);
  var docurl=file.getUrl();    
      for (nn=0;nn<viewersArray.length;++nn){
        MailApp.sendEmail(viewersArray[nn], 'your document', docurl);
          }
}

I first used 'editor' as variable name, now changed to 'viewers' to avoid confusion.

If you really need to include everybody in your domain to get access I guess the best solution would be to create a group with all users to simplify the process.

EDIT : there is maybe a simpler solution that is to move the file in a shared folder : all items in a folder have the same sharing parameters as the folder itself.

example :

function sharebyFolder(){
    var file = DocsList.getFileById('docId');
    var folder = DocsList.getFolderById('shared folder Id');
    file.addToFolder(folder)
      }