我的Google工作表系统会通过实时列表进行读取,并将自动发送的电子邮件发送给负责给定行内容的人员。
此列表包含日期,说明和受让人电子邮件等变量。该列表逐行运行,因此,由于我使用的代码,一个人可能会收到分配给它们的每一行的几封电子邮件。
我想更改代码,以便在列表中编译类似电子邮件地址,并在单个电子邮件中发送每行的内容(理想情况下格式化为表格)。我怎样才能做到这一点?
我目前使用的脚本如下:
function AssignmentEmail() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Assignments");
var range = sheet.getRange("A3:G950");
var info = range.getValues();
for (i in info) {
var col = info[i];
var date = Utilities.formatDate(col[0], "PST", "YYYY-MMM-dd");
var observation = col[1];
var lab = col[2];
var contact = col[3];
var action = col[4];
var email = col[6];
if (email="distribution list address") {
MailApp.sendEmail(email, "*Text and variables for group*");
}
else if (email!="") {
MailApp.sendEmail(email,"*Text and variables for individual*");
}
}
}
感谢您的帮助!
答案 0 :(得分:1)
您可以使用电子邮件地址作为键将每一行推送到dictionary中的数组。您可以使用JavaScript object执行此操作。字典会将您的数据存储在key
:value
对中,电子邮件地址为key
&一个value
数组,用于存储要发送到该地址的数据。你最终得到的是字典看起来有点像这样:
{"email.address@domain.tld": [['data row 1', 1, 'foo'],
['data row 2', 2, 'bar']
],
"another.email@domain.tld": [['only one data row', 0, 'baz']],
"group.email@domain.tld": [['1st of many', 10, 'lorem'],
['2nd row', 20, 'ipsum'],
['3rd row', 30, 'dolor'],
['Nth row', 100, 'si amet']
]
}
因此,您从数据行中提取电子邮件地址&在你的字典的键中查找该电子邮件:
填充字典后,您可以使用for(var key in dictionary){}
构造迭代键。您可以访问dictionary.key
或dictionary[key]
表单中每个键下的值。它只是一个带有名称而不是索引数字的数组! (实际上没有,但类比就足够了。)因此,您可以使用dictionary[key][0]
(或dictionary.key[0]
)形式在给定键下访问数组的第一个元素。 和您仍然可以使用key
中的值(在您的情况下是电子邮件地址),因此您可以撰写Logger.log("key = %s, values = %s", key, dictionary[key])
。
代码看起来像这样:
/*...connect to your data source as above...*/
var info = range.getValues();
/* Create an empty JS Object to provide our dictionary.
*+ we'll add each email address as a dict key as we see it.
*+ each key will point to an array which will be the data
*+ to be entered into each email to the recipient address (the key) */
var email_data_store = {};
for (i in info) {
var col = info[i];
/*...variable assignments as above...*/
var email = col[6];
if(email != ""){
if(!(email in email_data_store)){ // Does a key matching this email already exist?
// if not, create it:
email_data_store[email] = [];
// so now we have an empty array under the key `email`
}
email_data_store[email].push(/* an array of your values */);
}
}
// now iterate over the dict to format the emails & send
for(var email in email_data_store){
/* in here, iterate over the 2D arrays in email_data_store[email]
*+ You can use array notation to address all items,
*+ so that you don't have the potential confusion of
*+ mixing array & object notation */
for(var i = 0, lim = email_data_store[email].length; i < lim; ++i){
/* format your data here */
}
MailApp.sendEmail(email, /* your formatted email body */);
}
/* whatever cleanup you want to do before ending your function */
更多文档:MDN on JS Objects