使用Google脚本发送电子邮件

时间:2020-01-29 18:24:40

标签: google-apps-script google-sheets

有人可以帮助我通过Google脚本发送电子邮件吗?

在这里,我面临的挑战是第一列(电子邮件)的范围最多可以包含1000个电子邮件地址列表。虽然,现在(现在)工作正常,如何使它成为动态列表范围,以将我的电子邮件列表反馈给脚本。

代码:

// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'Email Success!';

/**
 * Sends non-duplicate emails with data from the current spreadsheet.
 */
function sendEmails2() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Script (Beta)");


  var startRow = 2; // First row of data to process
  var numRows = 3; // 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();

  for (var i = 0; i < data.length; ++i) {

    var row = data[i];
    var emailAddress = row[0];    // First column
    var message = row[1];         // Second column
    var emailSent = row[2];       // Third column


    if (emailSent !== EMAIL_SENT) { // Prevents sending duplicates

      var subject = '[Auto] The Process Has Not Yet Been Started';
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);

      // Make sure the cell is updated right away in case the script is interrupted

      SpreadsheetApp.flush();
    }
  }
}

Doc Link

1 个答案:

答案 0 :(得分:0)

为了使您的范围动态变化,可以使用Sheet.getLastRow(),它返回内容的最后一行的位置。

假设函数sendEmails2是您为此使用的函数,则只需修改变量numRows。您必须更改此行:

var numRows = 3; // Number of rows to process

对此:

var numRows = sheet.getLastRow() - startRow + 1;

参考:

我希望这会有所帮助。