首页 > 解决方案 > 根据单元格中的特定文本输入自动化电子邮件

问题描述

我在编写一个会自动从 Google 表格发送电子邮件的脚本时遇到困难。电子邮件应发送到位于 V 列的电子邮件地址,但只能在同一行的 AB 列输入“N”之后。它只会在进入后立即发生一次,并且不会再次发生。

我尝试了一些脚本,例如Google Apps Script - 根据单元格中的数据发送电子邮件,但没有成功。

标签: google-apps-script

解决方案


您需要遍历 AB 列并检查“N”条目(假设它只是一个字符串),然后发送电子邮件,然后,为避免再次发生,您可以将 N 更改为其他值。使用应用程序脚本,它看起来像这样:

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  // Will return a 2D array with the entire's sheet values 
  var data = sheet.getDataRange().getValues(); 

  for (var i = 0; i < data.length; i++){
    if (data[i][0] == "N"){
      // Sends the email, The name section is the name people who receive the email would see ass the "from" id.
      // If there is no email in the cell this will return an error, so you can add a try/catch here to avoid that.
      GmailApp.sendEmail(data[i][1], "Subject", "Message", {name: 'N Finder Script'});

      //To avoid repetition, you can edit the N value after sending the email.
      sheet.getRange("A" + (i+1)).setValue(""); // This would be "AB" in your case.
      sheet.getRange("A" + (i+1)).setValue("S"); // S for email sent, for example.
    }
  }
}

一些小警告;我用一个小的测试电子表格运行了这个,这就是我在“A”列中搜索值的原因。当我检查 data[i][0] 时,我正在检查第一列的第 i 行,您必须将 0 更改为与您拥有“N”的列匹配的数字。这同样适用于电子邮件,我在 data[i][1] 中查看它们,您将更改该 1 以匹配您拥有电子邮件列表的列。

最后,为了让代码在每次添加 N 时都运行,您可以添加一个 onEdit 触发器,您可以按照以下链接中的说明进行操作:

https://developers.google.com/apps-script/guides/triggers/installable


推荐阅读