如何修改此发送电子邮件代码以将范围扩展到多列?

时间:2016-11-17 15:49:51

标签: google-apps-script

我想从电子表格向多人发送电子邮件,但只向所有列中的信息发送电子邮件,而不仅仅是1.例如,我希望B2:E2中的所有信息都通过电子邮件发送到A2。

我使用的是我在下面附带的Google支持中提供的基本模板。

我所做的代码的所有更改都没有奏效:

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, 2)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  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";
    MailApp.sendEmail(emailAddress, subject, message);
  }
}

2 个答案:

答案 0 :(得分:1)

对原始脚本进行的修改很少,在这种情况下,html是我们的朋友,它看起来会更好。

代码:

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 2;   // Number of rows to process
  var colWidth = 5; // column width, including first one
  // Fetch the range of cells A2:E3, one email per row
  var dataRange = sheet.getRange(startRow, 1, numRows, colWidth)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  var subject = "Sending emails from a Spreadsheet";
  for (i in data) {
    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = '<body><div style="font-family:arial,sans;font-size:10pt"><p>welcome message</p>';  
    message+= '<table style="border-collapse:collapse;" border = 1 cellpadding = 4><tr>';
    for(var n=1 ; n<row.length ; n++){
      message += '<td bgcolor="#EEF">'+row[n]+'</td>'
    }
    message += '</tr></table></div></body>';  
    MailApp.sendEmail(emailAddress, subject, 'html only',{htmlBody:message});
  }
}

表单示例:

enter image description here

电子邮件结果,第三行:

enter image description here

答案 1 :(得分:0)

我已经设置了一个电子表格,我认为它模仿了您正在寻找的表格结构:

https://docs.google.com/spreadsheets/d/1S3fWaV4Sl4mIYjT-kMtOlP2V4xWSOpz721bxGWFuNqQ/edit

以下函数发送电子邮件:

  • 每行一封电子邮件
  • 第0列中的电子邮件地址,其他列中的数据

代码:

// The range of data including email columns
// Example is set up with email in Column A, data in B and C
// Headers on Row 1, data rows on 2 and 3.
var DATA_RANGE = 'A2:C3';

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getRange(DATA_RANGE);
  var values = data.getValues();

  for (var i = 0, row; row = values[i]; i++) {
    // Take email address from column A
    var emailAddress = row[0];
    // Join the remaining columns, comma-separated (as an example)
    var messageData = row.slice(1).join(', ');
    MailApp.sendEmail(emailAddress, 'Sending emails from a Spreadsheet', messageData);
  }
}

这是否涵盖了您尝试做的事情?