首页 > 解决方案 > 使用谷歌脚本发送电子邮件

问题描述

谁能帮我通过谷歌脚本发送电子邮件?

这里我面临的挑战是第一列(电子邮件)的范围可能多达 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();
    }
  }
}

文档链接

标签: google-apps-scriptgoogle-sheets

解决方案


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

假设该函数sendEmails2是您为此使用的函数,您只需要修改变量numRows. 您将不得不更改此行:

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

对此:

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

参考:

我希望这有任何帮助。


推荐阅读