简体   繁体   English

Google Spreadsheet-如何避免发送重复的电子邮件?

[英]Google Spreadsheet - How to avoid sending email duplicates?

I am having an issue with a script. 我的脚本有问题。 I used the following script from Google Developers Website in order to do a simple merge mail. 我使用了Google Developers网站上的以下脚本来编写简单的合并邮件。 See https://developers.google.com/apps-script/articles/mail_merge 参见https://developers.google.com/apps-script/articles/mail_merge

I modified a bit the script so to prevent email duplicates. 我对脚本进行了一些修改,以防止电子邮件重复。 However, even if the script seems to work as it marks 'EMAIL_SENT' in each row every time an email is sent. 但是,即使脚本似乎可以正常工作,因为每次发送电子邮件时,它都会在每行中标记为“ EMAIL_SENT”。 It does not pay attention if the mail as already been marked and still send the mail. 如果邮件已被标记并仍发送邮件,则不会引起注意。

I believe there is an error at line 16 "var emailSent = rowData[6];" 我相信第16行出现错误“ var emailSent = rowData [6];”

I would really appreciate if someone could help me. 如果有人可以帮助我,我将不胜感激。 Whoever you are thanks in advance. 无论您是谁,先谢谢您。

Here is the modified script : 这是修改后的脚本:

var EMAIL_SENT = "EMAIL_SENT";

function sendEmails() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = ss.getSheets()[0];
  var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 7);
  var templateSheet = ss.getSheets()[1];
  var emailTemplate = templateSheet.getRange("A2").getValue();
  var objects = getRowsData(dataSheet, dataRange);
  for (var i = 0; i < objects.length; ++i) {
    var Resume = DriveApp.getFilesByName('Resume.pdf') var Portfolio = DriveApp.getFilesByName('Portfolio.pdf') var rowData = objects[i];
    var emailText = fillInTemplateFromObject(emailTemplate, rowData);
    var emailSubject = "Architectural Internship";
    var emailSent = rowData[6];
    if (emailSent != EMAIL_SENT) {
      MailApp.sendEmail(rowData.emailAddress, emailSubject, emailText, {
        attachments: [Resume.next(), Portfolio.next()]
      });
      dataSheet.getRange(2 + i, 7).setValue(EMAIL_SENT);
      SpreadsheetApp.flush();
    }
  }
}

function fillInTemplateFromObject(template, data) {
  var email = template;
  var templateVars = template.match(/\${\"[^\"]+\"}/g);
  for (var i = 0; i < templateVars.length; ++i) {
    var variableData = data[normalizeHeader(templateVars[i])];
    email = email.replace(templateVars[i], variableData || "");
  }
  return email;
}

function getRowsData(sheet, range, columnHeadersRowIndex) {
  columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
  var numColumns = range.getEndColumn() - range.getColumn() + 1;
  var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
  var headers = headersRange.getValues()[0];
  return getObjects(range.getValues(), normalizeHeaders(headers));
}

function getObjects(data, keys) {
  var objects = [];
  for (var i = 0; i < data.length; ++i) {
    var object = {};
    var hasData = false;
    for (var j = 0; j < data[i].length; ++j) {
      var cellData = data[i][j];
      if (isCellEmpty(cellData)) {
        continue;
      }
      object[keys[j]] = cellData;
      hasData = true;
    }
    if (hasData) {
      objects.push(object);
    }
  }
  return objects;
}

function normalizeHeaders(headers) {
  var keys = [];
  for (var i = 0; i < headers.length; ++i) {
    var key = normalizeHeader(headers[i]);
    if (key.length > 0) {
      keys.push(key);
    }
  }
  return keys;
}

function normalizeHeader(header) {
  var key = "";
  var upperCase = false;
  for (var i = 0; i < header.length; ++i) {
    var letter = header[i];
    if (letter == " " && key.length > 0) {
      upperCase = true;
      continue;
    }
    if (!isAlnum(letter)) {
      continue;
    }
    if (key.length == 0 && isDigit(letter)) {
      continue;
    }
    if (upperCase) {
      upperCase = false;
      key += letter.toUpperCase();
    } else {
      key += letter.toLowerCase();
    }
  }
  return key;
}

// Returns true if the cell where cellData was read from is empty. // Arguments: // - cellData: string function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}

// Returns true if the character char is alphabetical, false otherwise. function isAlnum(char) { return char >= 'A' && char <= 'Z' || char >= 'a' && char <= 'z' || isDigit(char); }

// Returns true if the character char is a digit, false otherwise. function isDigit(char) { return char >= '0' && char <= '9'; }

I would recommend logging both values before executing to make sure they are the same. 我建议在执行之前记录两个值以确保它们相同。 I would also guess that the email_sent and EMAIL_SENT are different data types. 我还会猜到email_sent和EMAIL_SENT是不同的数据类型。 Can also try forcing the value to string for comparison. 也可以尝试将值强制为字符串以进行比较。

To clarify: 澄清:

logger.Log(emailSent);
logger.Log(EMAIL_SENT);
 if (emailSent.toString() != EMAIL_SENT.toString())
{...

Your code is really hard to read and the functions that return 2 or more objects make it even harder...you are using variable names that are also a bit confusing.... but that is probably a personal pov :-) 您的代码确实很难阅读,并且返回2个或更多对象的函数使其变得更加困难...您使用的变量名也有些令人困惑。...但这可能是个人观点:-)

Anyway, I think I've found the issue: when you write var rowData = objects[i]; 无论如何,我认为我已经找到了问题:当您编写var rowData = objects[i];

This "object" is actually the result of the getRowData function but if you look at this function, you'll see that it returns 2 objects, the first one being itself the result of another function (getObjects) ... 这个“对象”实际上是getRowData函数的结果,但是如果您看一下该函数,就会发现它返回了2个对象,第一个对象本身就是另一个函数(getObjects)的结果...

You are checking the value is the 6th element of the array which is actually an object and compare it to a string. 您正在检查该值是数组的第六个元素(实际上是一个对象),并将其与字符串进行比较。 The equality will never be true. 平等永远不会是正确的。

I didn't go further in the analyse since I found it really confusing ( as I already said) but at least you have a first element to check . 我没有做进一步的分析,因为我发现它确实令人困惑(正如我已经说过的那样),但至少您要检查第一个元素。

I would suggest you rewrite this code in a more simple way and use more appropriate variable names to help you while debugging. 我建议您以更简单的方式重写此代码,并在调试时使用更合适的变量名来帮助您。

Error is in this line of code - 这行代码中有错误-

var dataRange = sheet.getRange(startRow, 1, numRows, 2) var dataRange = sheet.getRange(startRow,1,numRows,2)

It's considering only 2 columns in the range. 它仅考虑范围内的2列。 Changed 2 to 3 and it worked fine. 将2更改为3,效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM