I'm pretty new to programming and don't really know Javascript. Recently, to help out my mother with her business, I've came up with the script below.
Basically it takes information from a sheet (the sheet is filled with answers from Google Forms), copy a template document and then replace some fields in the copied document with those informations.
Now what I'm trying to do is to export the filled document to PDF, can someone help?
Here's the actual script:
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var timestamp = e.values[0];
//client info
var nome = e.values[1];
var cpf = e.values[2];
var rg = e.values[3];
var rua = e.values[4];
var numero = e.values[5];
var bairro = e.values[6];
var cidade = e.values[7];
var estado = e.values[8];
var cep = e.values[9];
var celular = e.values[10];
//seller info
var nome_vendedor = e.values[11];
var cpf_vendedor = e.values[12];
//template is the template file, and you get it by ID
var template = DriveApp.getFileById('1VB5u4OrqIQO8P6scj-rzkjtRlZ8NI-ZKd9xGKfnEqBA');
//acess main folder
var mainfolder = DriveApp.getFolderById('1G6g2VyrvpKpqSvLei3_jefQMNsGb-be0');
//create a new folder
var newFolderId = mainfolder.createFolder(nome + ' ' + cpf).getId();
//get new folder Id
var id = DriveApp.getFolderById(newFolderId);
//copy the template file to the new folder
var copy = template.makeCopy(nome + ' ' + cpf, id);
//open the document by it's Id
var document = DocumentApp.openById(copy.getId());
//get to the doc body for the replace
var body = document.getBody();
////////////
////////////
////////////
////////////
////////////
//ReplaceText methods
////////////
////////////
////////////
////////////
//client info
body.replaceText('{{nome}}', nome);
body.replaceText('{{cpf}}', cpf);
body.replaceText('{{rg}}', rg);
body.replaceText('{{rua}}', rua);
body.replaceText('{{numero}}', numero);
body.replaceText('{{bairro}}', bairro);
body.replaceText('{{cidade}}', cidade);
body.replaceText('{{estado}}', estado);
body.replaceText('{{cep}}', cep);
body.replaceText('{{celular}}', celular);
//seller info
body.replaceText('{{nome_vendedor}}', nome_vendedor);
body.replaceText('{{cpf_vendedor}}', cpf_vendedor);
//save and close the document
document.saveAndClose();
}
The easiest way to export a Goolge Document to pdf is using the UrlFetchApp
You need the
basic export url
the file id
specofy export parameters if and as required
An access token that you can obtain with the ScriptApp
Sample snippet based on you code before where you already have the document id:
var url = "https://docs.google.com/document/d/"+id+"/export?";
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
+'&top_margin=0.50'
+'&bottom_margin=0.50'
+'&left_margin=0.50'
+'&right_margin=0.50'
// other parameters if you need
/*
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false' // hide page numbers
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
*/
var response = UrlFetchApp.fetch(url + url_ext,
{
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
},
muteHttpExceptions:true
});
DriveApp.createFile(response.getBlob().setName("myPdf"));
Related
I want to e-mail an individual sheet tab as a PDF using script. This script below will send the entire workbook/sheet as a PDF file (which is a great start, but not ideal). However, I am only interested in e-mailing the specific sheet tab named "Alpha".
function sendpdf() {
var originalSpreadsheet = SpreadsheetApp.getActive();
var message = 'Hello, \n\n' + 'Attached is the priority list for today.';
var subject = "Priority List for - " + new Date().toString();
var emailTo = "first#example.com,second#example.com";
var pdf = DriveApp.getFileById(originalSpreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:'PRIORITY.pdf',content:pdf, mimeType:'application/pdf'};
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
}
I am using the script below to export a sheet as Excel file but the output file name is always Document Name + Sheet Name ("Exported - Report.xlsx"). How can I modify this to only use the sheet name as file name of the exported file ("Report.xlsx")?
function ExportSheet()
{
var SheetApp = SpreadsheetApp.getActive();
SheetApp.rename("Exported");
ShtURL = SheetApp.getUrl();
ShtID = SheetApp.getId();
ShtGID = SheetApp.getSheetId();
var url = ShtURL.toString().replace("/edit", "/export?format=xlsx&gid=" + ShtGID);
var html = HtmlService.createHtmlOutput('<html><script>'
+'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
+'if(document.createEvent){'
+' var event=document.createEvent("MouseEvents");'
+' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+' event.initEvent("click",true,true); a.dispatchEvent(event);'
+'}else{ a.click() }'
+'close();'
+'</script>'
// Offer URL as clickable link in case above code fails.
+'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+'</html>')
.setWidth( 90 ).setHeight( 1 );
SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );
SheetApp.rename("Template");
}
In your situation, unfortunately, using the URL of ShtURL.toString().replace("/edit", "/export?format=xlsx&gid=" + ShtGID), the filename cannot be directly changed. So, in this case, how about the following modification?
Modified script:
function ExportSheet() {
var SheetApp = SpreadsheetApp.getActive();
SheetApp.rename("Exported");
ShtURL = SheetApp.getUrl();
ShtID = SheetApp.getId();
ShtGID = SheetApp.getSheetId();
var url = ShtURL.toString().replace("/edit", "/export?format=xlsx&gid=" + ShtGID);
// --- I modified below script.
var blob = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob();
var file = DriveApp.createFile(blob.setName(SheetApp.getSheets()[0].getSheetName()));
url = "https://drive.google.com/uc?export=download&id=" + file.getId();
// ---
var html = HtmlService.createHtmlOutput('<html><script>'
+ 'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+ 'var a = document.createElement("a"); a.href="' + url + '"; a.target="_blank";'
+ 'if(document.createEvent){'
+ ' var event=document.createEvent("MouseEvents");'
+ ' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+ ' event.initEvent("click",true,true); a.dispatchEvent(event);'
+ '}else{ a.click() }'
+ 'close();'
+ '</script>'
// Offer URL as clickable link in case above code fails.
+ '<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+ '<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+ '</html>')
.setWidth(90).setHeight(1);
SpreadsheetApp.getUi().showModalDialog(html, "Opening ...");
SheetApp.rename("Template");
file.setTrashed(true); // Added
}
In this modification, the converted XLSX is created as a temporal file. Here, the filename is changed. And, the file is downloaded using the URL of the created file. The temporal file is removed.
Note:
From your script, I thought that you might have wanted to use the sheet name of the 1st tab. But, if you want to give the specific filename, please modify SheetApp.getSheets()[0].getSheetName() of blob.setName(SheetApp.getSheets()[0].getSheetName()).
I know there are two separate email functions in the code but the one I am trying to get to work is the sendsheettopdfwithA2mailaddress.
Every time I try to delete the other one I get an error message so any help with deleting that and everything still work would be greatly appreciated too. The error message is
Exception: Request failed for docs.google.com returned code 401. Truncated server response: <HTML><HEAD>
The main issue that I'm having is that I only want to email one sheet which is the main one or 0. When it sends the email it sends 12 different sheets and sheet 0 is very condensed to about a quarter of the sheet.
/** #OnlyCurrentDoc */
function onEdit(e) {
var ss = SpreadsheetApp.getActive() //gets the active spreadsheet
var sheet = SpreadsheetApp.getActiveSheet() //gets the active sheet
var cell = ss.getActiveRange() //gets the active cell
var cellContent = cell.getValue() //gets the value of the active cell
if(cellContent === 'BOXCHECKED') {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('B1:H4').activate();
var currentCell = spreadsheet.getCurrentCell();
spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
currentCell.activateAsCurrentCell();
currentCell = spreadsheet.getCurrentCell();
spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
currentCell.activateAsCurrentCell();
spreadsheet.getRange('A1:H55').activate();
spreadsheet.getRange('A1').activate();
spreadsheet.getCurrentCell().setFormula('=H5');
spreadsheet.getRange('H56').activate();
spreadsheet.insertSheet(1);
spreadsheet.getRange('\'Quote Sheet\'!A1:H55').copyTo(spreadsheet.getActiveRange(),
SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
spreadsheet.getRange('\'Quote Sheet\'!A1:H55').copyTo(spreadsheet.getActiveRange(),
SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
spreadsheet.getActiveSheet().setHiddenGridlines(true);
spreadsheet.getActiveSheet().hideSheet();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Data Sheets'), true);
spreadsheet.getRange('2:35').activate();
spreadsheet.getActiveSheet().insertRowsBefore(spreadsheet.getActiveRange().getRow(), 34);
spreadsheet.getActiveRange().offset(0, 0, 34,
spreadsheet.getActiveRange().getNumColumns()).activate();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Quote Sheet'), true);
spreadsheet.getRange('B11').activate();
currentCell = spreadsheet.getCurrentCell();
spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.NEXT).activate();
currentCell.activateAsCurrentCell();
currentCell = spreadsheet.getCurrentCell();
spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.NEXT).activate();
currentCell.activateAsCurrentCell();
currentCell = spreadsheet.getCurrentCell();
spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.NEXT).activate();
currentCell.activateAsCurrentCell();
currentCell = spreadsheet.getCurrentCell();
spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
currentCell.activateAsCurrentCell();
currentCell = spreadsheet.getCurrentCell();
spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
currentCell.activateAsCurrentCell();
currentCell = spreadsheet.getCurrentCell();
spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.UP).activate();
currentCell.activateAsCurrentCell();
spreadsheet.getRange('A12:z44').activate();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Data Sheets'), true);
spreadsheet.getRange('\'Quote Sheet\'!A12:z44').copyTo(spreadsheet.getActiveRange(),
SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Quote Sheet'), true);
spreadsheet.getRangeList(['C5:C10', 'H6:H10', 'B12:B44','D12:E44', 'H49:H50','B51:E55']).activate();
spreadsheet.setCurrentCell(spreadsheet.getRange('H49'));
spreadsheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true});
spreadsheet.getRange('C5').activate();
SpreadsheetApp.getActive();
spreadsheet.getRange('G53').activate();
spreadsheet.getCurrentCell().setValue('False')
SpreadsheetApp.getActive();
spreadsheet.getRange('A1').activate();
spreadsheet.getCurrentCell().setValue('Quote Sheet')
SpreadsheetApp.getActive().getSheets().forEach(function (sh)
{
sh.setName(sh.getRange('a1').getValue())
})
}
};
function renameSheets() {
SpreadsheetApp.getActive().getSheets().forEach(function (sh) {
sh.setName(sh.getRange('A1').getValue())
})
};
/* Email Google Spreadsheet as PDF */
function emailGoogleSpreadsheetAsPDF() {
// Send the PDF of the spreadsheet to this email address
var email = "t.mitchellbivens#gmail.com";
// Get the currently active spreadsheet URL (link)
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Subject of email message
var subject = "PDF generated from spreadsheet " + ss.getName();
// Email Body can be HTML too
var body = "Install the <a href='http://www.labnol.org/email-sheet'>Email Spreadsheet add-on</a> for
one-click conversion.";
var blob = DriveApp.getFileById(ss.getId()).getAs("application/pdf");
blob.setName(ss.getName() + ".pdf");
// If allowed to send emails, send the email with the PDF attachment
if (MailApp.getRemainingDailyQuota() > 0)
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments:[blob]
});
};
function sendSheetToPdfwithA2MailAdress() { // this is the function to call
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheets()[0]; // it will send sheet 0 which is the first sheet in the spreadsheet.
// if you change the number, change it also in the parameters below
var shName = sh.getName()
sendSpreadsheetToPdf(0, shName, sh.getRange('A2').getValue()," Test Run ", "Let's Hope This Works");
}
function sendSpreadsheetToPdf(sheetNumber, pdfName, email,subject, htmlbody) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheetId = spreadsheet.getId()
var sheetId = sheetNumber ? spreadsheet.getSheets()[sheetNumber].getSheetId() : 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=A4' // paper size
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true' // fit to width, false for actual size
+ '&fith=true' // fit to height, false for actual size
+ '&sheetnames=true&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
}
MailApp.sendEmail(
email,
subject+" (" + pdfName +")",
"html content only",
mailOptions);
}
};
The macro works when i run it separately but when i place it in the onEdit function it won't work.
Take a look on Simple Triggers Restrictions
Quote:
They cannot access services that require authorization. For example, a simple trigger cannot send an email because the Gmail service requires authorization, but a simple trigger can translate a phrase with the Language service, which is anonymous.
If you had used installable triggers instead, you would've had less restrictions (like being able to send emails)
From OP's comment in the question, it's clear that an important part of the code comes from a macro created using the Google Sheets Macro Recorder. Using this tool and the mouse to jump from one cell or range to another, creates a lot of .activate() methods which are very slow and it's very likely that this is the causing problems due to the maximum execution limit for simple triggers.
The execution time could be reduced a lot either by recording again the macro but instead of using the mouse use the Go to range or the named range box to select the ranges to be modified or by refactoring the script. See my answer to Service Spreadsheet Time Out - Optimizing Macro script? for details.
I'm trying to send an image and spreadsheet chart in an email together but I can only send one or the other. For example, i can only send images and the chart will not appear and if i send charts the images will not appear. I'm also new to this, thanks for the help.
{
function emailCharts(sheet,emails,emailSubject){
DriveApp.getRootFolder()
var targetspreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Active spreadsheet of the key file
var sheet = targetspreadsheet.getSheetByName('Test'); // Change the sheet name Eg.'IPQC Overall Tracker' to your sheet name
var emailSubject = 'Scratches Awareness Program Test';
var emails = 'example#gmail.com'; // your email ID
var charts = sheet.getCharts();
if(charts.length==0){
MailApp.sendEmail({
to: emails,
subject: "ERROR:"+emailSubject,
htmlBody: "No charts in the spreadsheet"});
return;
}
var emailStarting = "<br>########TEST##########<br>"
var emailEnding = "#################################<br>"
var emailSignature = "<br>Best Regards, <br>############<br><br> This is an automated generated email. No signature is required."
var chartBlobs=new Array(charts.length);
var emailBody="Hi Everyone,<br>" + emailStarting;
var emailImages={};
for(var i=0;i<charts.length;i++){
var builder = charts[i].modify();
builder.setOption('vAxis.format', '#');
var newchart = builder.build();
chartBlobs[i]= newchart.getAs('image/png');
emailBody= emailBody + "<p align='center'><img src='cid:chart"+i+"'></p>" ;
emailImages["chart"+i]= chartBlobs[i];
}
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
var requestData = {"method": "GET",
"headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
var googleLogoUrl = "https://i.imgur.com/vO6IJVG.png";
var youtubeLogoUrl =
"https://i.imgur.com/xMqvjHf.jpg";
var googleLogoBlob = UrlFetchApp
.fetch(googleLogoUrl)
.getBlob()
.setName("Scratches Alert");
var youtubeLogoBlob = UrlFetchApp
.fetch(youtubeLogoUrl)
.getBlob()
.setName("Scratches Dashboard");
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody + emailEnding + emailSignature,
inlineImages:emailImages, attachments:[{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"}],googleLogo: googleLogoBlob,youtubeLogo: youtubeLogoBlob});
}
}
You want to send the images of charts, googleLogoBlob and youtubeLogoBlob as the inline images, and want to send Excel file (xlsx format) as the attachment file.
You want to achieve this using Google Apps Script.
I could understand like this. If my understanding is correct, how about this modification? Please think of this as just one of several answers.
Modification points:
format=xlsx is used for converting Google Spreadsheet to Excel.
{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"} is used as the attachment file.
Please modify to {fileName:sheetName+".xlsx", content:contents, mimeType: MimeType.MICROSOFT_EXCEL}.
googleLogo: googleLogoBlob,youtubeLogo: youtubeLogoBlob is directly used as the object for MailApp.sendEmail(object). And googleLogo and youtubeLogo are not included in the inline images.
Please include those image to the inline images.
When above points are reflected to your script, it becomes as follows.
Modified script:
Please modify your script as follows.
From:
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ssID;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
var googleLogoUrl = "https://i.imgur.com/vO6IJVG.png";
var youtubeLogoUrl =
"https://i.imgur.com/xMqvjHf.jpg";
var googleLogoBlob = UrlFetchApp
.fetch(googleLogoUrl)
.getBlob()
.setName("Scratches Alert");
var youtubeLogoBlob = UrlFetchApp
.fetch(youtubeLogoUrl)
.getBlob()
.setName("Scratches Dashboard");
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody + emailEnding + emailSignature,
inlineImages:emailImages, attachments:[{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"}],googleLogo: googleLogoBlob,youtubeLogo: youtubeLogoBlob});
}
}
To:
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx"; // Modified
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
var googleLogoUrl = "https://i.imgur.com/vO6IJVG.png";
var youtubeLogoUrl = "https://i.imgur.com/xMqvjHf.jpg";
var googleLogoBlob = UrlFetchApp.fetch(googleLogoUrl).getBlob().setName("Scratches Alert");
var youtubeLogoBlob = UrlFetchApp.fetch(youtubeLogoUrl).getBlob().setName("Scratches Dashboard");
emailBody += "<img src='cid:googleLogo'><img src='cid:youtubeLogo'>"; // Added
emailImages.googleLogo = googleLogoBlob; // Added
emailImages.youtubeLogo = youtubeLogoBlob; // Added
MailApp.sendEmail({ // Modified
to: emails,
subject: emailSubject,
htmlBody: emailBody + emailEnding + emailSignature,
inlineImages: emailImages,
attachments: [{fileName: sheetName+".xlsx", content: contents, mimeType: MimeType.MICROSOFT_EXCEL}],
});
}
Note:
About googleLogo and youtubeLogo, please modify <img src='cid:googleLogo'><img src='cid:youtubeLogo'> for your actual situation.
References:
sendEmail(message)
Enum MimeType
Your code is fine, the only isssue you are having is the way you're building your MailApp.sendEmail() . Do it in this way:
var emails = "example#gmail.com";
var emailSubject = "Test Subject";
var body = emailBody + emailEnding + emailSignature;
var spreadsheetObj = {
fileName:sheetName+".xls",
content:contents,
mimeType:"application//xls"
};
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: body,
attachments: [ spreadsheetObj, googleLogoBlob, youtubeLogoBlob]
});
The attachments must be an array, you were building it in the wrong way. As the Docs says:
attachments BlobSource[] An array of files to send with the email (see example)
Notice:
If you attach several files, the email can take some time to be delivered.
I have a piece of code here which, on form submission, is supposed to:
Perform some calculations in a spreadsheet using the form responses, create a pdf file containing the user's results, and email this to them.
I have set up a trigger which runs "onFormSubmit", with events "From Spreadsheet", "onFormSubmit" and Here is my code:
//Set out global variables
var docTemplate = "1Ff3SfcXQyGeCe8-Y24l4EUMU7P9TsgREsAYO9W6RE2o";
var docName="Calculations";
//createOnFormSubmitTrigger();
function onFormSubmit(e){
//Variables
var ssID = '1dMmihZoJqfLoZs9e7YMoeUb_IobW4k6BbOuMDOTTLGk';
var ss = SpreadsheetApp.openById(ssID);
ss.setActiveSheet(ss.getSheetByName("Sheet3"));
var totalOutstandingPrincipalDebt = SpreadsheetApp.getActiveSheet().getRange("G25").getValue();
var totalOutstandingInterest = SpreadsheetApp.getActiveSheet().getRange("H25").getValue();
var totalOutstandingCompensation = SpreadsheetApp.getActiveSheet().getRange("I25").getValue();
var dailyInterestRate = SpreadsheetApp.getActiveSheet().getRange("J25").getValue();
var grandTotal = SpreadsheetApp.getActiveSheet().getRange("K25").getValue();
var userEmail = SpreadsheetApp.getActiveSheet().getRange("H24").getValue();
//Template Info
var copyId=DriveApp.getFileById(docTemplate).makeCopy(docName+' for '+userEmail).getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
//Putting the data into the file
copyBody.insertParagraph(1,'Total Outstanding Principal Debt: £' + totalOutstandingPrincipalDebt);
copyBody.insertParagraph(2,'Total Outstanding Interest: £'+ totalOutstandingInterest );
copyBody.insertParagraph(3,'Total Outstanding Compensation: £'+ totalOutstandingCompensation);
copyBody.insertParagraph(4,'Grand Total: £' + grandTotal);
copyBody.insertParagraph(5,'Daily Interest Rate: £'+ dailyInterestRate);
copyDoc.saveAndClose();
//email pdf document as attachment
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
var subject = "Calculations";
var body = "Thank you very much for using our online calculator. Please find your results attached.";
MailApp.sendEmail(userEmail, subject, body, {htmlBody: body, attachments: pdf});
//Deletes temporary Document
DriveApp.getFileById(copyId).setTrashed(true);
}
The script will sometimes run fine when I am in the script editor (not always?!), but when I submit a form, I receive the following error notification: "Failed to send email: no recipient (line 40, file "Code")", where line 40 is the line:
MailApp.sendEmail(userEmail, subject, body, {htmlBody: body, attachments: pdf});
I have tried using getNote() instead of getValue() for the userEmail variable but that didn't work either! I have also made sure the cell reference on the spreadsheet is formatted as plain text rather than as a number, but I'm not sure what else to try now! Any suggestions would be greatly appreciated!
Thanks so much in advance :)
It's working now since I changed:
var ssID = '1dMmihZoJqfLoZs9e7Y.............';
var ss = SpreadsheetApp.openById(ssID);
ss.setActiveSheet(ss.getSheetByName("Sheet3"));
var totalOutstandingPrincipalDebt = SpreadsheetApp.getActiveSheet().getRange("G25").getValue();
var totalOutstandingInterest = SpreadsheetApp.getActiveSheet().getRange("H25").getValue();
var totalOutstandingCompensation = SpreadsheetApp.getActiveSheet().getRange("I25").getValue();
var dailyInterestRate = SpreadsheetApp.getActiveSheet().getRange("J25").getValue();
var grandTotal = SpreadsheetApp.getActiveSheet().getRange("K25").getValue();
var userEmail = SpreadsheetApp.getActiveSheet().getRange("H24").getValue();
to:
var ssID = '1dMmihZ.................';
var ss = SpreadsheetApp.openById(ssID);
var sheet = SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);
var totalOutstandingPrincipalDebt = sheet.getRange("G25").getValue();
var totalOutstandingInterest = sheet.getRange("H25").getValue();
var totalOutstandingCompensation = sheet.getRange("I25").getValue();
var dailyInterestRate = sheet.getRange("J25").getValue();
var grandTotal = sheet.getRange("K25").getValue();
var userEmail = sheet.getRange("H24").getValue();