Everything works but the subject line blank... why? What am I missing? - google-apps-script

I think this must be very easy to see, but I cannot see it! This script sends out a sheet as a PDF. It works well, except that the subject line is blank. I've tried substituting an actual string for the variable in the class gmailApp at the bottom, but the subject line is still blank when the email arrives. Help! Thank you.
P.S.-- note that I took out the email address for privacy.
function emailPDF(email, subject, body, sheetName) {
var email = "...";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Client');
var cost = sheet.getSheetValues(1,1,1,1).toLocaleString();
var subject = ss.getName();
var body = "Hi Serenity, the material cost is $" + cost +" Thank you!";
// Base URL
var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());
/* Specify PDF export parameters
From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
*/
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
headers : {
'Authorization' : 'Bearer ' + token
}
}).getBlob().setName(ss.getName() + ".pdf");
// save PDF to drive
// var newFile = DriveApp.createFile(response).setName(sheet.getName() + ".pdf")
if (MailApp.getRemainingDailyQuota() > 0)
GmailApp.sendEmail(email, subject, body, {
htmlBody : body,
attachments : [response]
});
}

I've figured it out... this was just petty error. The spreadsheet has a lot of scripts. I picked up this script from a month ago, started from scratch and accidentally gave it the same function name. Both scripts were being called simultaneously, causing this result. Everything works now.
I appreciate your comment Lamblichus... I was so focused on the script being wrong that I didn't realize what was happening. Then I realized that it can't be wrong. You got me thinking the right way. Best.

Related

Exception: Request failed for https://docs.google.com returned code 400

My response is :
Exception: Request failed for https://docs.google.com returned code 400. Truncated server response: <meta nam... (use muteHttpExceptions option to examine full response)
could anyone help me please ? Thank you ! (i'm french... sorry ;)
My code is :
function emailSpreadsheetAsPDF() {
DocumentApp.getActiveDocument();
DriveApp.getFiles();
// This is the link to my spreadsheet with the Form responses and the Notification of Absence Template sheet
// Add the link to your spreadsheet here
// or you can just replace the text in the link between "d/" and "/edit"
// In my case is the text: 1Kj4U5hrIPiRAjceHkySUlLFXjckh75R-KVqn0IsNrjA
const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1ktAc1lf1lhQ9xf04sRm18l-8GQurW4eqnqrldbBNYj8/edit");
// We are going to get the email address from the cell "A1" from the "Notification of Absence" sheet
// Change the reference of the cell or the name of the sheet if it is different
const value = ss.getSheetByName("NOA PDF").getRange("a1").getValue();
const email = value.toString();
// Subject of the email message
const subject = 'Notification of Absence Form';
// Email Text.
const body = "Hello Cerian, <br/> <br/> Please find attached a Notification of Absence Form. <br/> This has also been automatically saved to the Sickness folder, but will need to be sorted into the correct employee's file. <br/> <br/> Sickness Folder - https://drive.google.com/drive/folders/1SCPGzH4fz7ryna7SSuXSTtYbJlJ52r0U?usp=sharing.";
// Again, the URL to your spreadsheet but now with "/export" at the end
// Change it to the link of your spreadsheet, but leave the "/export"
const url = 'https://docs.google.com/spreadsheets/d/1ktAc1lf1lhQ9xf04sRm18l-8GQurW4eqnqrldbBNYj8/export?';
const exportOptions =
'exportFormat=pdf&format=pdf' + // export as pdf
'&size=a4' + // paper size letter / You can use A4 or legal
'&portrait=true' + // orientation portal, use false for landscape
'&fitw=true' + // fit to page width false, to get the actual size
'&sheetnames=false&printtitle=false' + // hide optional headers and footers
'&pagenumbers=false&gridlines=false' + // hide page numbers and gridlines
'&fzr=false' + // do not repeat row headers (frozen rows) on each page
'&gid=852132144'; // the sheet's Id. Change it to your sheet ID.
// You can find the sheet ID in the link bar.
// Select the sheet that you want to print and check the link,
// the gid number of the sheet is on the end of your link.
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
// Generate the PDF file
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
// Send the PDF file as an attachement
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments: [{
fileName: "Notification of Absence Form" + ".pdf",
content: response.getBytes(),
mimeType: "application/pdf"
}]
});
// Save the PDF to Drive. The name of the PDF is going to be the name of the employee (cell b9)
const nameFile = ss.getSheetByName("NoA PDF").getRange("b9").getValue().toString() +".pdf"
DriveApp.createFile(response.setName(nameFile));
var files = DriveApp.getRootFolder().getFiles();
while (files.hasNext()) {
var file = files.next();
var destination = DriveApp.getFolderById("1SCPGzH4fz7ryna7SSuXSTtYbJlJ52r0U");
destination.addFile(file);
var pull = DriveApp.getRootFolder();
pull.removeFile(file);
}
}

urlfetchapp.fetch <url> are not permitted ERROR in Google Apps Script

I had a Google Apps Script code bound to a Google Spreadsheet that created a PDF file from one of its sheets using the urlfetchapp.fetch(url, options) function. Yesterday, without editing the code, it suddenly stopped working, showing the error "urlfetchapp.fetch are not permitted".
I checked other spreadsheet bound code I made for other Spreadsheet and it is not working anymore either, same error.
For context, I am using Google Workspace for my company, and dealing with sensitive data. But it was working just fine up until yesterday.
function CrearPDFysubirloalDrive(){
var Ss = SpreadsheetApp.getActiveSpreadsheet();
var Sheet= Ss.getSheetByName("Name")
var Longitud = Sheet.getLastRow();
var range = Sheet.getRange(1,1,Longitud,10);
var docId ="Planning";
var docId1Semana = Sheet.getRange('F5').getValue();
var docIdRevision = Sheet.getRange('C7').getValue();
var pdfname= docId+ " W"+docId1Semana+"-Rev "+docIdRevision;
//This is not important to the question
var tempst= Sheet.copyTo(Ss).setName(pdfname);
tempst.insertColumns(1);
tempst.setRowHeight(1,30)
tempst.setColumnWidth(1, 20);
tempst.setColumnWidth(12, 30);
tempst.deleteColumns(13,tempst.getMaxColumns()-12)
//tempst.deleteRows(Longitud+2, (tempst.getMaxRows()- (Longitud+2)))
tempst.getRange("A4:A5").setBackground("white");
var drawing = tempst.getDrawings();
for (let i=0; i<drawing.length;i++){
drawing[i].remove();
}
SpreadsheetApp.flush();
//THIS PART IS GIVING THE ERROR
var url = 'https://docs.google.com/spreadsheets/d/{ID}/export?'.replace('{ID}', Ss.getId());
var exportOptions = 'exportFormat=pdf&format=pdf' + // export as pdf / csv / xls / xlsx
'&size=letter' + // paper size legal / letter / A4
'&portrait=true' + // orientation, false for landscape
'&fitw=true&source=labnol' + // fit to page width, false for actual size
'&sheetnames=false&printtitle=false' + // hide optional headers and footers
'&pagenumbers=false&gridlines=false' + // hide page numbers and gridlines
'&fzr=false' + // do not repeat row headers (frozen rows) on each page
'&top_margin=0.40' + //All four margins must be set!
'&bottom_margin=0.00' + //All four margins must be set!
'&left_margin=0.40' + //All four margins must be set!
'&right_margin=0.40' + //All four margins must be set!
'&gridlines=false' + //true/false
'&gid=' + tempst.getSheetId(); // the sheet's Id
var token = ScriptApp.getOAuthToken();
var blob = UrlFetchApp.fetch(url + exportOptions, {
headers: {
Authorization: 'Bearer '+token
}
}).getBlob().setName(tempst.getName()+".pdf");
var pdfFile = DriveApp.createFile(blob);
var FolderDestino= DriveApp.getFolderById(<FOLDERID>);
FolderDestino.createFile(blob.setName(pdfname))
I am not an expert at coding by any means, but I suspect it is related to the Oauth token. Either that or the function has been deprecated.
EXACT ERROR CODE:
Exception: UrlFetch calls to https://docs.google.com/spreadsheets/d/*******/export?exportFormat=pdf&format=pdf&size=letter&portrait=true&fitw=true&source=labnol&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&fzr=false&top_margin=0.40&bottom_margin=0.00&left_margin=0.40&right_margin=0.40&gridlines=false&gid=2141838874 are not permitted.
Any help?
Thank you in advance
It seems like there is a bug
The issue has already been filed on Google's Issue Tracker. I recommend you to "star" it to increase visibility.

How to get the “shareable link” of a Google Drive file via Google Apps Script and paste the link into a cell in Google Sheets?

I have a script that makes a PDF of my invoice and sends it to a Google drive folder.Now I want to get the "Shareable link" from the file it just made and paste it into a specific Cell in google Sheets. I don't have a coding background and at most I can understand and modify some code. So I'm using code I found online to create the PDF. I tried making my own code for the shareable link but I'm getting nowhere. Can anyone help me. This is the code I'm using for the PDF. If I can provide any more useful information please let me know. Thank you! :)
// Get the currently active spreadsheet URL (link)
var ss = SpreadsheetApp.getActiveSpreadsheet();
var token = ScriptApp.getOAuthToken();
var sheet = ss.getSheetByName("Invoice");
//Creating an exportable URL
var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());
var folderID = "#### Folder ID ####"; // Folder id to save in a folder.
var folder = DriveApp.getFolderById(folderID);
var invoiceNumber = ss.getRange("'Invoice'!I16").getValue()
var InvoiceDate = ss.getRange("!I17").getValue()
var pdfName = "Invoice #"+ invoiceNumber + " - " + Utilities.formatDate(new Date(), "GMT-7", "MM-dd-yyyy");
/* Specify PDF export parameters
From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
*/
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
// Convert individual worksheet to PDF
var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
headers: {
'Authorization': 'Bearer ' + token
}
});
//convert the response to a blob
var blobs = response.getBlob().setName(pdfName + '.pdf');
//saves the file to the specified folder of Google Drive
var newFile = folder.createFile(blobs);
// Define the scope
Logger.log("Storage Space used: " + DriveApp.getStorageUsed());
}```
Intuitively, you can achieve a lot only by yourself, and this is the way to go at the beginning:
You want to retrieve the link of the pdf, so you know for sure that it can happen only when the pdf has been created, which is after this line var newFile = folder.createFile(blobs);
Therefore newFile is the PDF you've created, what's left is just to get the link of this file, you can use either getUrl() or getId():
var newFileLink = newFile.getUrl()
or
var newFileLink = "http://drive.google.com/uc?export=view&id=" + newFile.getId()
Now you have stored the link of the created PDF, and you want to write data into your spreadsheet within a specific cell, maybe you want it in J16, since you're using invoiceNumber = ss.getRange("'Invoice'!I16").getValue() to get a value from I16
Assuming you want to set a value in J16. Intuitively again, since getValue retrieve something, so maybe something link setValue will do the opposite:
var writePDFLink = ss.getRange("'Invoice'!J16").setValue(newFileLink)
Hope this was insightful.

print spreadsheet as pdf with no margins

I am trying to make things easier for my team so I want to have them print out a given area from my Google Sheets document into a pdf with predefined margins/printing settings. The printed area is not on the active spreadsheet.
I just moved over from Excel to Spreadsheets. I know some VBA but do not really know that much about GAS. I did quite a lot of research but all the samples I found are based on UiApp which not supported any longer.
I found some threads (where I think messages are missing?):
https://plus.google.com/u/1/115432608459317672860/posts/DQTbozyTsKk?cfem=1&pageId=none
Google Apps Script print sheet with margins
The last one I found was this one (PDF margins - Google Script) where I added the settings for margins (does it work that way though? I could not try it out yet because I do not know how to download the pdf. I tried do research but couldn't find anything..
var report = SpreadsheetApp.getActive();
var pdfName = "Angebot";
var sheetName = "Angebot";
var sourceSheet = report.getSheetByName(sheetName);
SpreadsheetApp.getActiveSpreadsheet().toast('Creating the PDF');
// export url
var url = 'https://docs.google.com/spreadsheets/d/'+report.getId()+'/export?exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=A4' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='+sourceSheet.getSheetId(); // the sheet's Id
+ '&top_margin=0'
+ '&left_margin=0'
+ '&right_margin=0'
+ '&bottom_margin=0'
var token = ScriptApp.getOAuthToken();
// request export url
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var theBlob = response.getBlob().setName(pdfName+'.pdf');
//var attach = {fileName:'Monthly Report.pdf',content:pdf, mimeType:'application/pdf'};
var name = report.getRange("H1:H1").getValues(); // Get Name
var emailTo = report.getRange("H2:H2").getValues(); // Get email
var period = report.getRange("H3:H3").getValues(); // Get Reporting Period
var subject = " - TEST Monthly Report - " + period; // Construct the Subject Line
var message = "Hi " + name + ", here is your latest report for " + period; // email body text
// download pdf
}

Email Google spreadsheet failed authorization with Oauth 2.0

The below scrip to email a google spreadsheet as a pdf worked perfectly until last week. Now I get this message: "Authorization is required to perform that action". After reading up on it, I understand that Google no longer supports OAuth 1.0.
Can anyone guide me in the right direction towards updating the script for oAuth 2.0?
function EmailSpreadsheetAsPdf() {
// Google spreadsheet (key) + sheet (gid)
var key = "1XJDY-M2oSfIG6AQ3IYv4SwKn_QmPW2m24ZNB38o7vCw";
var gid = "1593627730";
// Email recipient
var emailTo = “testuser#gmail.com";
var subject = “This is the subject”;
var body = “This is the body“;
var filename = “Example" + ".pdf";
// Make OAuth Connection
var oauthConfig = UrlFetchApp.addOAuthService("google");
var scope = "https://docs.google.com/feeds"
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=" + scope);
oauthConfig.setAuthorizationUrl("https://accounts.google.com/OAuthAuthorizeToken");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
var request = {
"method": "GET",
"muteHttpExceptions": true,
"oAuthServiceName": "google",
"oAuthUseToken": "always",
};
// Create the PDF using this hack with special option variables in the URL
// As of 2/4/14 this seems to be the only way to export PDF with custom options (landscape, no gridlines, etc)
// exportFormat = pdf / csv / xls / xlsx
// gridlines = true / false
// printtitle = true (1) / false (0)
// size = legal / letter/ A4 (according to: http://goo.gl/nPrfdj, but doesn't seem to work?? letter only)
// fzr (repeat frozen rows) = true / false
// portrait = true (1) / false (0)
// fitw (fit to page width) = true (1) / false (0)
// add gid if to export a particular sheet - 0, 1, 2,..
//define the params URL to fetch
var params = "?gid=" + gid + "&fitw=true&exportFormat=pdf&format=pdf&size=A4&portrait=false&sheetnames=false&printtitle=false&gridlines=false";
//fetching file url
var blob = UrlFetchApp.fetch("https://docs.google.com/" + "spreadsheets/d/" + key + "/export" + params, request);
var pdf = blob.getBlob().setName(filename);
// Send the email with attachment
GmailApp.sendEmail(emailTo, subject, body, {attachments:[pdf]});
}
Google ressources: https://developers.google.com/identity/protocols/OAuth_ref
I finally solved my own question. I didn't even need to setup anything in the develop console, see my solution below. The fist time you run it, it will promt you to authorize access to your gmail. I hope it will be helpful to someone.
function EmailSpreadsheetAsPdf() {
// Google spreadsheet (key) + sheet (gid)
var key = "1XJDY-M2oSfIG6AQ3IYv4SwKn_QmPW2m24ZNB38o7vCw";
var gid = "1593627730";
// Email recipient
var emailTo = “testuser#gmail.com";
var subject = “This is the subject”;
var body = “This is the body“;
var filename = “Example" + ".pdf";
// Base URL
var url = "https://docs.google.com/spreadsheets/d/" + key + "/export?";
/* Specify PDF export parameters
From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
*/
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=false' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
var token = ScriptApp.getOAuthToken();
// Convert worksheet to PDF
var pdf = UrlFetchApp.fetch(url + url_ext + gid, {
headers: {
'Authorization': 'Bearer ' + token
}
});
// Send email with PDF attachment
GmailApp.sendEmail(emailTo, subject, body, {
attachments:[pdf]
});
}