在郵件中傳送 HTML 內容
在上面的示例中,如果我們要將 HTML 內容作為訊息傳送到電子郵件中,則通過轉到檔案 - >新建 - > HTML 檔案來建立 HTML 檔案
現在你可以看到除 gs 檔案之外的 HTML 檔案,如下所示:
現在,從上面的示例更新 getMessage()
方法,如下所示:
function getMessage(name, amount) {
var htmlOutput = HtmlService.createHtmlOutputFromFile('Message'); // Message is the name of the HTML file
var message = htmlOutput.getContent()
message = message.replace("%name", name);
message = message.replace("%amount", amount);
return message;
}
對 MailApp api 的呼叫也需要更改
MailApp.sendEmail(recipientEmail, subject, message, {htmlBody : message});
所以整個程式碼如下:
function getDataSheet() {
sheet = SpreadsheetApp.getActiveSheet();
startRow = 2; // First row of data to process
numRows = 100; // Number of rows to process
startCol = 1; //First column of data to process
numCols = 15; // Number of columns to process
var dataRange = sheet.getRange(startRow, startCol, numRows, numCols);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
return data;
}
function getMessage(name, amount) {
var htmlOutput = HtmlService.createHtmlOutputFromFile('Message');
var message = htmlOutput.getContent()
message = message.replace("%name", name);
message = message.replace("%amount", amount);
return message;
}
function sendEmail() {
var emailSent = "Yes";
var reimbursed = "Yes";
var emailCol = 5;
var data = getDataSheet();
for (var i = 0; i < data.length; i++) {
var row = data[i];
var isReimbursed = row[3];
var isEmailSent = row[4];
var name = row[0];
var amount = row[2];
if(isReimbursed == reimbursed && isEmailSent != emailSent) {
var subject = "Reimbursement details";
var message = getMessage(name, amount);
var recipientEmail = row[1];
MailApp.sendEmail(recipientEmail, subject, message, {htmlBody : message});
sheet.getRange(startRow + i, emailCol).setValue(emailSent);
}
}
}