สร้าง function MailMerge3() ตามนี้
function MailMerge3() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
SalarySheet=SpreadsheetApp.setActiveSheet(ss.getSheetByName("Salary")),
TemplateID='1bjpQnJikYMGYNaJQhetpZpkHyjI7iqBqDufprzMSo4k',
header = "A1:G1",
data="A2:G6",
dataRows = SalarySheet.getRange(data).getValues(),
headerRow = SalarySheet.getRange(header).getValues(),
numColumns = SalarySheet.getRange(header).getNumColumns(),
emailText = "";
for (var i=0 ; i < dataRows.length ; i++) {
emailText="";
var id =DriveApp.getFileById(TemplateID).makeCopy("กองคลัง : แจ้งการโอนเงินให้คุณ " + dataRows[i][0] + " " + dataRows[i][1]).getId(),
doc=DocumentApp.openById(id),
docBody=doc.getBody();
for (var j = 0 ; j < numColumns -1 ; j++) {
docBody.replaceText('{' + headerRow[0][j] + '}' , dataRows[i][j]);
}
emailText=docBody.getText();
doc.saveAndClose();
var emailaddress=dataRows[i][2],
subject = "กองคลัง : แจ้งการโอนเงินให้คุณ " + dataRows[i][0] + " " + dataRows[i][1],
attachment = DocumentApp.openById(id);
MailApp.sendEmail( emailaddress,
subject ,
emailText,
{
attachments: [attachment.getAs(MimeType.PDF)]
}
);
try {
dataRows[i][numColumns-1] = new Date();
} catch (e) {
dataRows[i][numColumns-1] = e.message;
}
}
SalarySheet.getRange(data).setValues(dataRows);
}
Comments are closed.