通过脚本自动化Google工作表,将电子邮件发送到同一行的电子邮件

时间:2018-01-01 19:24:19

标签: google-apps-script google-sheets

我在下面的脚本中发送电子邮件到输入到特定列的电子邮件地址,当是的是输入特定列时。

我对此代码的一个问题是,我不确定如何一次向两个以上的接收者发送电子邮件。

此外,此脚本不适用于链接到Google表单的工作表。经过研究后,我发现脚本不起作用的原因是脚本不会在onedit触发器上运行,但只有在链接到google Forms时才会在定时触发器上运行。

请有人完成上述任务。

EmailScript() {
 var ss = SpreadsheetApp.getActiveSpreadsheet(); 
  var sheet = ss.getSheetByName("Repairs");
  // Sets "range" from A2 (2,1) to Bottom right cell of sheet (MaxRow,MaxColumn)
  var range = sheet.getRange(2,1,sheet.getMaxRows()-1,sheet.getMaxColumns());
  var data = range.getValues()
  var activeRng,activeCell,columnToCheck,editedColumn,editedRow,newValue,sh,ss,valueToTestFor;//Define variables without assigning a value


  //USER INPUT
    columnToCheck = 9 ;//Column A is 1
    valueToTestFor = "Y"
  //END OF USER INPUT

  ss = SpreadsheetApp.getActiveSpreadsheet();//Get the active spreadsheet
  sh = ss.getActiveSheet();//Get the active sheet tab
  activeRng = SpreadsheetApp.getActiveRange();//Get the active range
  activeCell = activeRng.getCell(1, 1);//Get the first cell in the active range
  newValue = activeCell.getValue();//Get the new value in the cell that was just edited
  editedColumn = activeCell.getColumn();//Get the column of the cell that was just edited
  editedRow = activeCell.getRow();//Get the row of the cell that was just edited

  if (editedColumn !== columnToCheck) {//Only run the code if the column to monitor is the correct one   
  return;

}

// Loops through data, 0 to the "length" of the data, set above (dictated by range), with i to be each row number with each loop, and row[X] representing Column X for row i.
    for (var i = 0; i < data.length; ++i) {

// Setting all variables for email messages
// Column A = row[0], Column B = row[1],C2,D3,E4,F5,G6,H7,I8,J9,K10,L11,M12,N13,O14,P15,Q16,R17,S18,T19,U20,V21,W22,X23 
    var row = data[i];

    var firstname = row[0];
    var email = row[1];
    var email2 = row [2];
    var email3 = row [4];
    var emailstatus = row[13]
    var emailPattern = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|aero|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|name|museum|name|net|org|pro|tel|travel)\b/;
    var validEmailAddress = emailPattern.test(email); 

    if (newValue === valueToTestFor && emailstatus != "EMAIL_SENT") {    

        var message = "<HTML><BODY>"
        + "<P>Dear " + firstname + ","
        + "<br /><br />"
        +" Your device has been repaired"
        + "<br /><br />"    
        + "Regards"
        + "<br /><br />" 
        + "Test"
        + "<br /><br />"
        + "</HTML></BODY>";      
      MailApp.sendEmail({
        to:email, 
        cc:email2,
        bbc:email3,
        subject:"Device Repair",
        htmlBody: message});   

   sheet.getRange(i+2,10).setValue("EMAIL_SENT");   

    } 
}
}

提前感谢您的帮助。

0 个答案:

没有答案