I tried to email invoices to customers as PDF file with appscript. Here is my function :
function sendPDF() {
var data = getBody("DATA");
var emailData = rowsToObjects(data);
emailData.forEach(function (rowObject) {
rincianTemplate(rowObject)
DocumentApp.getActiveDocument();
DriveApp.getFiles();
const ss = SpreadsheetApp.getActiveSpreadsheet();
const url = 'https://docs.google.com/spreadsheets/d/SS_ID/export?'.replace('SS_ID', ss.getId());
const exportOptions =
'exportFormat=pdf&format=pdf' + // export as pdf
'&size=3.59x4.48' + //A3/A4/A5/B4/B5/letter/tabloid/legal/statement/executive/folio
'&portrait=true' + // orientation portal, use false for landscape
'&scale=3' + //1= Normal 100% / 2= Fit to width / 3= Fit to height / 4= Fit to Page
'&top_margin=0' +
'&bottom_margin=0' +
'&left_margin=0' +
'&right_margin=0' +
'&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=1720281854'; // 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()}};
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
var templateData = getData("TEMPLATE");
var emailSubjectTemplate = templateData[1][0]; //Cell A2
var emailBodyTemplate = templateData[4][0]; //Cell A5
var subject = renderTemplate(emailSubjectTemplate, rowObject);
var body = renderTemplate(emailBodyTemplate, rowObject);
var email = rowObject['EMAIL'];
MailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments: [{
fileName: "RINCIAN TAGIHAN.pdf",
content: response.getBytes(),
mimeType: "application/pdf"
}]
}
);
});
}
The function works well exceipt for the Invoices PDF send the same data (1st listed customer's invoice) to all listed customers. Please enlighten me :)