1

I have a script on my Google sheets that sends out a sheet converted as PDF to a mailing list. This script is set up on many different spreadsheets, but I found that some of them were starting to fail in the last coupe of days.

Error content is:

Exception: Request failed for https://docs.google.com returned code 500. Truncated server response: <meta name="viewport" c... (use muteHttpExceptions option to examine full response)

It seems that OAuthToken is not working on these spreadsheets, but it is working on others.

Here is the code:

        function sendSheetToPdf(){ // this is the function to call
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sh = SpreadsheetApp.getActive().getSheetByName('Acknowledged Orders'); 
      // if you change the number, change it also in the parameters below
      
      
      var ssC = SpreadsheetApp.getActive().getSheetByName('Acknowledged Orders')
      var toEmail = ""
      var shName = sh.getName()
      
      if (sh.getRange("A11").getValue()!="Rows") {
      
      sendSpreadsheetToPdf(sh, shName, toEmail,"Daily Acknowledged Orders", "Daily Acknowledged Orders");
        
      }
    }
    function sendSpreadsheetToPdf(sheetNumber, pdfName, email,subject, htmlbody) {
      var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
      var spreadsheetId = spreadsheet.getId()  
      var sheetId = sheetNumber ? '0' : null;  
      var url_base = spreadsheet.getUrl().replace(/edit$/,'');
    
      var url_ext = 'export?exportFormat=pdf&format=pdf'   //export as pdf
    
          + (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId)) 
          // following parameters are optional...
          + '&size=A3'      // paper size
          + '&portrait=true'    // orientation, false for landscape
          + '&fitw=true'        // fit to width, false for actual size
          + '&sheetnames=false&printtitle=false&pagenumbers=true'  //hide optional headers and footers
          + '&gridlines=false'  // hide gridlines
          + '&fzr=false';       // do not repeat row headers (frozen rows) on each page
    
      var options = {
        headers: {
          'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken(),
        }
      }
    
       var response = UrlFetchApp.fetch(url_base + url_ext, options);
      var blob = response.getBlob().setName(pdfName + '.pdf');
      if (email) {
        var mailOptions = {
          attachments:blob, htmlBody:htmlbody  
        }
        
        var ccEmail = ""
        
    MailApp.sendEmail(
          email+","+ccEmail, 
          subject+" (" + pdfName +")", 
          "html content only", 
          mailOptions);
    
      }
    }

The response received:

<!DOCTYPE html><html lang="en"><head><meta name="description" content="Web word processing, presentations and spreadsheets"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"><link rel="shortcut icon" href="//ssl.gstatic.com/docs/common/drive_favicon1.ico"><title>Error</title><meta name="referrer" content="origin"><link href="//fonts.googleapis.com/css?family=Product+Sans" rel="stylesheet" type="text/css"><style nonce="VuOBJHMXpK2pKNeVo731zA">/* Copyright 2020 Google Inc. All Rights Reserved. */
.goog-inline-block{position:relative;display:-moz-inline-box;display:inline-block}* html .goog-inline-block{display:inline}*:first-child+html .goog-inline-block{display:inline}#drive-logo{margin:18px 0;position:absolute;white-space:nowrap}.docs-drivelogo-img{background-image:url('//ssl.gstatic.com/images/branding/googlelogo/1x/googlelogo_color_116x41dp.png');background-size:116px 41px;display:inline-block;height:41px;vertical-align:bottom;width:116px}.docs-drivelogo-text{color:#000;display:inline-block;opacity:0.54;text-decoration:none;font-family:'Product Sans',Arial,Helvetica,sans-serif;font-size:32px;text-rendering:optimizeLegibility;position:relative;top:-6px;left:-7px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}@media (-webkit-min-device-pixel-ratio:1.5),(min-resolution:144dpi){.docs-drivelogo-img{background-image:url('//ssl.gstatic.com/images/branding/googlelogo/2x/googlelogo_color_116x41dp.png')}}</style><style type="text/css" nonce="VuOBJHMXpK2pKNeVo731zA">body {background-color: #fff; font-family: Arial,sans-serif; font-size: 13px; margin: 0; padding: 0;}a, a:link, a:visited {color: #112ABB;}</style><style type="text/css" nonce="VuOBJHMXpK2pKNeVo731zA">.errorMessage {font-size: 12pt; font-weight: bold; line-height: 150%;}</style></head><body><div id="outerContainer"><div id="innerContainer"><div style="position: absolute; top: -80px;"><div style="margin: 18px 0; position: absolute; white-space: nowrap;"><a href="//support.google.com/docs/"><img height="35px" src="//ssl.gstatic.com/docs/common/product/spreadsheets_lockup1.png" alt="Google logo"/></a></div></div><p style="padding-top: 15px">Google Docs encountered an error. Please try reloading this page, or coming back to it in a few minutes.</p><p>To learn more about the Google Docs editors, please visit our <a href="https://support.google.com/docs/?hl=en&p=error_help" target="_blank">help center</a>.</p><p><br><b>We're sorry for the inconvenience.</b><br><i>- The Google Docs Team</i></p></div></div></body><style nonce="VuOBJHMXpK2pKNeVo731zA">html {height: 100%; overflow: auto;}body {height: 100%; overflow: auto;}#outerContainer {margin: auto; max-width: 750px;}#innerContainer {margin-bottom: 20px; margin-left: 40px; margin-right: 40px; margin-top: 80px; position: relative;}</style></html>
Justin Yu
  • 101
  • 2
  • 5
  • 2
    It's not clear to me. What's spreadsheets are you referring to? Hopefully you don't mean the ones that are converted to pdf because of course those are no longer spreadsheets at all. – Cooper Jul 10 '20 at 16:00
  • 1
    May be related: https://stackoverflow.com/questions/62770318/ – TheMaster Jul 10 '20 at 16:08
  • @Cooper One of the sheets in the spreadsheet gets converted to PDF then sent via email. I think the issue is with OAuthToken, but it's weird how it is working on other google sheets and not on others. Script is exactly the same on all of them. – Justin Yu Jul 10 '20 at 17:09
  • 1
    Yeah but I still don’t know what spreadsheet you’re talking about – Cooper Jul 10 '20 at 17:56
  • 1
    I think Oauth2 credentials are created in cloud console and projects are associated with cloud projects so if you are copying spreadsheets then your creating new projects and those projects probably need to be connected to the cloud project in order to have access to oauth2 credentials. Note: I'm not real strong in this area but I have a couple of projects that require oauth2 credentials. – Cooper Jul 10 '20 at 18:59
  • first of all, please, include the response in full (you can include it via a code snippet [ctrl+M] - it is perfectly runnable, or extract an error message). I have some experience with Google's OAuth2.0 implementations, and it looks like Cooper is probably right here - when you create a copy of a spreadsheet, it is assigned a default cloud project that you need to manually change to the old one or reauthorize the script. Also `500` error code might indicate that the error is beyond something you can do - Google uses a bunch of data centers all other the world to store and serve data - maybe... – Oleg Valter is with Ukraine Jul 10 '20 at 21:26
  • ...you got "lucky" this time (this is why one of the common fixes "try creating a new spreadsheet" is usually effective) - faulty server, ho knows. You will need to mute HTTP exceptions to extract the html from the response. Maybe the *actual* error message will shed some light on the matter – Oleg Valter is with Ukraine Jul 10 '20 at 21:27
  • Since `/export` is a semi-official endoint, it is difficult to tell what exactly went wrong. Please do provide the error content snippet regardless (btw, error *code* is always a number in HTTP, and this is the *message* or *body* you are speaking about [to be precise, this is an HTML string]). Usually, `5xx` error codes are not something you can fix (unless you are making a request to a braindead server that lacks error handling and fails to parse your payload due to bumping in an edge case) – Oleg Valter is with Ukraine Jul 10 '20 at 21:34
  • 1
    Hi @OlegValter, thank you for your comments. I updated the original post with the muteHTTPexceptions. Thank you! – Justin Yu Jul 10 '20 at 23:40
  • @JustinYu - thanks for providing the error (btw, you can insert snippets with Ctrl-M - please, always do that if the code is parsable / runnable). It is very likely that you cannot do anything to alleviate the issue other than going to [issue tracker](https://issuetracker.google.com/). The only thing I can suggest - can you show what the `url_base` looks like? – Oleg Valter is with Ukraine Jul 10 '20 at 23:48
  • 1
    Do these not working Sheets have an image attached? – Jescanellas Jul 13 '20 at 10:40
  • @Jescanellas yes, there is an image on the sheet. Weird thing is, the sheets that are working with the same script also have an image. – Justin Yu Jul 13 '20 at 19:11
  • 1
    Just an update - I just created an exact copy of the spreadsheets with the same exact script and it works fine. I guess there is an issue on Google's end and somehow messed up these couple of spreadsheets. Thanks for your help everyone! – Justin Yu Jul 13 '20 at 23:45
  • @JustinYu - glad you solved it. This is a common fix for Google Sheets issues of category "that should work, but does not" - Google has a lot of data centers, this time you probably got lucky ( or the new ID assigned to the new spreadsheet was ok - given the `5xx` error, who knows what went wrong ) – Oleg Valter is with Ukraine Jul 14 '20 at 00:18
  • @JustinYu - oh, and one question out of curiousity - what are the sheet and spreadsheet id of the old spreadsheet, could you provide them? I have an idea, but the error is not reproducible in my playground spreadsheet – Oleg Valter is with Ukraine Jul 14 '20 at 02:07
  • 1
    Nice to see the problem solved. If you could reproduce this again, please report it on Google's [Issue Tracker](https://issuetracker.google.com/issues/new?component=191640&template=823905). Thanks! – Jescanellas Jul 14 '20 at 14:21

1 Answers1

-1

I think you need to check the url. It was my case

Kateridzhe
  • 227
  • 3
  • 4