从Google表格脚本发送的电子邮件消息中的特定文本超链接

时间:2020-05-05 21:24:14

标签: google-apps-script google-sheets html-email

我想向此代码行引用的电子邮件中的文本的特定部分添加超链接: var message = row[2]; // Third column

我尝试了此建议<p> Please check out my <a href=https://example.com>site</a>,但我不知道如何将其插入htmlbody的变量中。我还尝试在脚本中对实际的电子邮件消息进行硬编码,但始终收到错误。

完整代码:

// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';

/**
 * Sends non-duplicate emails with data from the current spreadsheet.
 */
function sendEmails2() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2; // First row of data to process
  var numRows = 1000; // Number of rows to process
  // Fetch the range of cells A2:D1000
  var dataRange = sheet.getRange(startRow, 1, numRows, 1000);
  // 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 subject = row[1]; // Second column
    var message = row[2]; // Third column
    var emailSent = row[3]; // Fourth column
    if (emailSent !== EMAIL_SENT) { // Prevents sending duplicates
      MailApp.sendEmail(emailAddress, subject, "", {
        htmlBody: message.replace(/\n/g,'<br>')});
      sheet.getRange(startRow + i, 4).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}```

1 个答案:

答案 0 :(得分:0)

TL; DR

使用MailApp.sendEmail(emailAddress, subject, '', options)

看看选项sendEmail(recipient, subject, body, options)

分步指南:

  1. 使用以下数据填充工作表: enter image description here
  2. 打开Apps脚本并放置此代码
function sendEmail() {

  let data = SpreadsheetApp.getActiveSheet().getRange("A1:C1").getValues()
  
  let emailAddress = data[0][0]; 
  let subject = data[0][1]; 
  let message = data[0][2];

  let options = {
    htmlBody: `<a href="https://google.com">${message}</a>`
  }
  
  MailApp.sendEmail(emailAddress, subject, '', options);

}
  1. 运行您的代码并检查收件箱。您会看到类似的内容

enter image description here