2017-06-17 96 views
0

我有以下脚本根据表单提交中的一个字段发送电子邮件给适当的人。它正在正常工作,但每次提交新条目时它都会发送多封电子邮件,我不知道为什么。有人能告诉我我的代码中有什么问题来解决这个问题吗?在新的表单提交条目上发送重复的电子邮件

function sendEmails() { 
    var sheet = SpreadsheetApp.getActiveSheet(); 
    var startRow = 2; // First row of data to process 
    var numRows = 2; // Number of rows to process 
    // Fetch the range of cells A2:B3 
    var dataRange = sheet.getRange(startRow, 1, numRows, 3) 
    // Fetch values for each row in the Range. 
    var data = dataRange.getValues(); 
    var email1 = "[email protected]"; 
    var email2 = "[email protected]"; 
    for (i in data) { 
    var row = data[i]; 
    var emailAddress = row[0]; // First column 
    var message = row[1];  // Second column 
    var subject = "Sending emails from a Spreadsheet"; 
    if (message = "cat") { 
    MailApp.sendEmail(email1, subject, message); 
    if (message = "dog") { 
    MailApp.sendEmail(email2, subject, message); 
    } 
    } 
    } 
     } 
+1

使用改进的==或===以测试等效于你的if语句。因为这两个项目都评估为真。 – ScampMichael

+0

@ScampMichael尝试了你的建议,但没有运气,它仍然发送多个。就好像它不是只检查新行来确定发送电子邮件的位置,而是检查所有行。我不知道如何解决这个问题。 –

+0

有多少email1和多少email2? – ScampMichael

回答

1

我敢肯定表单提交的最后一行结束,并通过行迭代是不必要的。这假定你没有用数组公式和你的表单提交表格。

function sendEmails() { 
    var sheet = SpreadsheetApp.getActiveSheet(); 
    var row = sheet.getLastRow(); 
    var dataRange = sheet.getRange(row, 1, 1, sheet.getLastColumn()); 
    var data = dataRange.getValues()[0]; 

    var email1 = "[email protected]"; 
    var email2 = "[email protected]"; 

    var emailAddress = data[0]; // First column 
    var message = data[1];  // Second column 
    var subject = "Sending emails from a Spreadsheet"; 

    if (message == "cat") { 
    MailApp.sendEmail(email1, subject, message); 
    }; 
    if (message == "dog") { 
    MailApp.sendEmail(email2, subject, message); 
    }; 
    } 

最后一部分也许可以与桑迪的建议或开关>情况下

+0

非常感谢您的帮助!它现在有效!我真的很感激它。 –

2

这些行:

if (message = "cat") { 
    MailApp.sendEmail(email1, subject, message); 
if (message = "dog") { 
    MailApp.sendEmail(email2, subject, message); 
} 

应该是:

var email;//Create a new variable 

if (message == "cat") { 
    email = email1; 
} else if (message == "dog") { 
    email = email2; 
} 

MailApp.sendEmail(email, subject, message); 
+0

非常感谢你@sandygood感谢你的帮助,我现在能够得到这个工作。 –

相关问题