问题描述
嗨,
我对 javascript、谷歌应用程序脚本和一般编码比较陌生。我目前正在使用 Google 表格 [g-sheet] 的 Google Apps Script [g-script] 环境中工作。这是我想要完成的:
我有一个从工作表中获取数据的代码块。然后我有一个定义的函数来使用 for 循环发送电子邮件。在该 for 循环中,我尝试使用 HTMLService 类从文件创建模板,填充模板数量 [在本例中为 3],每行的数据都是唯一的,并将其存储为 var“htmlBody”。然后,使用 MailApp 类发送唯一创建的 HTML 模板。
我收到的错误:
当我运行代码时,我收到一个“行未定义”的引用错误。我添加了执行日志的图片。 console.log(boatData[i]) 语句是一个努力的故障排除 & 是记录到控制台的数据集中第一行的信息。
我该如何解决这个问题?
代码:
var sheet = SpreadsheetApp.getActive().getSheetByName('DB.charters');
var startRow = 3 ;
var numRows = 3 ;
var datarange = sheet.getRange(startRow,1,numRows,15);
var boatData = datarange.getValues();
function sendEmail() {
for (var i in boatData) {
var row = boatData[i] ;
function getEmailHtml() { // gets the HTML template & makes it useable
var htmlTemplate = HtmlService.createTemplateFromFile("emailTempWorkOrder.html"); // uses HtmlService class to create an HtmlTemplate object from the file in the code editor
htmlTemplate.boats = boatData[i] ; //makes the var boatData avail within the template through the proeprty .boats
console.log(boatData[i]); // logs the first row only
var htmlBody = htmlTemplate.evaluate().getContent(); // converts the html file into raw binary content for HTTP responses
return htmlBody;
} // end of getEmailHtml()
var htmlBody = getEmailHtml();
MailApp.sendEmail({ // Sends the email formatted
to: "bmsbreaux@gmail.com",subject: `Vessel Charter: ${row[1]} -`,// ${row[3]} [Client] [Date @ Time]
htmlBody: htmlBody,}); // end of MailApp action
} // end of for-loop
} // end of sendEmail()
// Confirmation statement.
console.log('Ran sendEmailWorkOrder(),sent emails');
解决方法
我刚刚运行了你的代码,运行良好,没有错误; 但如果我是你,我会像这样制作我的代码,它也能工作。
function sendEmail() {
const sheet = SpreadsheetApp.getActive().getSheetByName('DB.charters');
const boatData = sheet.getRange(3,1,3,15).getValues();
let htmlBody = HtmlService.createHtmlOutputFromFile("emailTempWorkOrder.html").getContent();
for (var i in boatData) {
var row = boatData[i] ;
htmlBody = htmlBody.replace('{boat}',boatData[i]);
MailApp.sendEmail({ // Sends the email formatted
to: "bmsbreaux@gmail.com",subject: `Vessel Charter: ${row[1]} -`,// ${row[3]} [Client] [Date @ Time]
htmlBody: htmlBody,}); // end of MailApp action
} // end of for-loop
} // end of sendEmail()
// Confirmation statement.
console.log('Ran sendEmailWorkOrder(),sent emails');
以下是html文件:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
{boat}
</body>
</html>