I've been trying to solve this but am new to programming. I'd like to send emails with invoice attachments from a sheet. The sheet holds all necessary info such as invoice number, invoice file name, file drive id, customer email etc.
The code I'm using for this is recycled from another apps script, which works. It doesn't seem to survive the modifications I'm trying here.
function invoiceDispatcher() {
const invoiceDispatcherSheet = SpreadsheetApp.openById("SPREADSHEETID").getSheetByName("invoicedispatcherlog");
let emailTemplate = HtmlService.createTemplateFromFile("invoiceEmailTemplate");
let invoiceNumber = 0;
let invoiceDate = 9;
let customerEmail = 8;
let invoiceName = 1;
let invoiceFileID = 2;
let transactionData = invoiceDispatcherSheet.getRange(2,1,invoiceDispatcherSheet.getLastRow()-1,13).getValues();
let cleanData = transactionData.filter(function (cases){ return cases[11] === true});
cleanData.forEach(function(row){
emailTemplate.rn = row[invoiceNumber];
emailTemplate.rd = Utilities.formatDate(row[invoiceDate], "CEST" , "dd.MM.yyyy");
//let invoiceFileName = String(row[1]);
let invoiceFile = DriveApp.getFileById(invoiceFileID).getAs(MimeType.PDF);
//let invoiceFile = DriveApp.getFilesByName([invoiceFileName]);
let invoiceMessage = emailTemplate.evaluate().getContent();
GmailApp.sendEmail(
row[customerEmail], "Your Invoice Document " row[invoiceNumber],
"Please open this message in an HTML-compatible email client. Thank you",
{name: "Company Name", htmlBody: invoiceMessage, attachments: [invoiceFile]});
})
}
Additionally, I'd like to add a timestamp to column K (Col10) of the sheet.
I'm sure I have some redundancies in here and am not at a point where I can fully appreciate all aspects of how functions and methods interlock but would be enormously grateful for some guidance. Please let me know if any of this was unclear and if I can provide further info.
CodePudding user response:
Try this:
function invoiceDispatcher() {
const sh = SpreadsheetApp.openById("SPREADSHEETID").getSheetByName("invoicedispatcherlog");
let t = HtmlService.createTemplateFromFile("invoiceEmailTemplate");
let transactionData = sh.getRange(2, 1, sh.getLastRow() - 1, 13).getValues();
let cleanData = transactionData.filter(function (cases) { return cases[11] == true });
cleanData.forEach(function (row) {
t.rn = row[0];
t.rd = Utilities.formatDate(row[9], "CEST", "dd.MM.yyyy");
let invoiceFile = DriveApp.getFileById(row[2]).getAs(MimeType.PDF);
let invoiceMessage = t.evaluate().getContent();
GmailApp.sendEmail(row[8], "Your Invoice Document " row[0],
"Please open this message in an HTML-compatible email client. Thank you",
{ name: "Company Name", htmlBody: invoiceMessage, attachments: [invoiceFile] });
})
}