我尝试创建一个脚本,该脚本从google文档中的电子表格中读取值(名称,日期等),并自定义要发送给具有这些值的用户的特定表单的描述(文本内容)。但是string.replace()方法不像我期望的那样工作。它只是替换了没有任何东西的钥匙。我错过了什么吗?我花了几个小时谷歌搜索没有答案。任何帮助将不胜感激。
var docId = ScriptProperties.getProperty("QuestionnaireDocId");
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 1000000; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 5)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var name = row[0]; // this var isn't empty. - tested it to check
var formSpreadsheet = SpreadsheetApp.openById(docId);
var sFormUrl = formSpreadsheet.getFormUrl();
if(sFormUrl) {
var response = UrlFetchApp.fetch(sFormUrl);
var sFormContent = response.getContentText();
//Replace <keyName> in the form description with the value of var 'name'
sFormContent = sFormContent.replace("<keyName>", name);
//get only body content
sFormContent = sFormContent.replace(/[\s\S]+<body[^>]*>([\s\S]+)<\/body>[\s\S]+/i, '$1');
//remove script
sFormContent = sFormContent.replace(/<script[^>]*>[\s\S]*<\/script>/i, '');
//add inline style for form elements, since gmail does not allow style tag and link tag to style it
sFormContent = sFormContent.replace(/class\=\"errorbox-good\"/gi, 'class="errorbox-good" style="margin-bottom:1.5em;zoom:1"');
sFormContent = sFormContent.replace(/class\=\"ss-q-title\"/gi, 'class="ss-q-title" style="display:block;font-weight:bold;"');
sFormContent = sFormContent.replace(/class\=\"ss-q-help\"/gi, 'class="ss-q-help" style="display:block;color:#666;margin:.1em 0 .25em 0"');
sFormContent = sFormContent.replace(/class\=\"ss-choices\"/gi, 'class="ss-choices" style="list-style:none;margin:.5em 0 0 0;padding:0;"');
}
var mailBody2;
if(sFormUrl) {
mailBody2 = '<br /><br />If you have trouble viewing or submitting this form, you can fill it out online:<br />';
mailBody2 += '<a href="' + sFormUrl + '" title="">' + sFormUrl + '</a>';
mailBody2 += '</body></html>';
mailBody2 += '<br /><br />';
mailBody2 += sFormContent;
mailBody2 += '<br />';
}
// Embed form and send the email - the emails work fine
var subject = "Test email";
MailApp.sendEmail(email_address, subject, mailBody2, {htmlBody: mailBody2});
}
答案 0 :(得分:1)
看起来有一些事情正在发生,因为这不能像书面那样工作。首先,在您从UrlFetchApp调用中返回的表单内容中,有两个表单描述显示的位置。一个看起来像这样。我只是把foo放在我的表单的描述字段中:
<meta itemprop="description" content="foo <keyName>">
另一个看起来像这样:
<div class="ss-form-desc ss-no-ignore-whitespace">foo </div>
第二个实例是实际显示在您的电子邮件中的实例,正如您所看到的,似乎已经被剥离了。我的猜测是它正在剥离任何看起来像HTML的东西。
所以这就是我尝试过的,这对我有用。在表单描述中,输入[keyName]而不是。
然后,您还需要全局搜索和替换,而不仅仅是[keyName]的第一个实例,以确保您在两个地方都能获得它。所以改变这一行:
sFormContent = sFormContent.replace("<keyName>", name);
到此:
sFormContent = sFormContent.replace(/\[keyName\]/g, name);
一旦我做了这些更改,我就能让它工作,我收到的电子邮件中包含说明中的电子表格中的值,在'foo'之后。