【问题标题】:How to run script if gmail subject contains " "如果 gmail 主题包含“”,如何运行脚本
【发布时间】:2020-03-14 03:09:33
【问题描述】:

我有一个脚本可以将 CSV gmail 附件导入到谷歌表格,它每分钟运行一次。我有另一个将数据复制到另一张工作表的脚本,我想包括在导入 CSV 脚本IF 之后运行的复制脚本@电子邮件主题行包含“一天结束的销售细节”。这种情况每天发生一次,主题行全天都包含“销售详情”。

在导入 CSV 后需要一点延迟以确保所有内容都得到充分处理,如果主题行包含预期的字符串,将使用 Utilities.sleep() 实现。

导入 CSV 脚本:

function importCSVFromGmail() { 
  //gets first(latest) message with set label
  var threads = GmailApp.getUserLabelByName('South Loop Sales').getThreads(0,1);     
  var message = threads[0].getMessages()[0];
  var attachment = message.getAttachments()[0];

  // Is the attachment a CSV file
  attachment.setContentTypeFromExtension();
  if (attachment.getContentType() === "text/csv") {                            
    var ss = SpreadsheetApp.getActive();
    var sh = ss.getSheetByName("Silverware-Sales");
    //parses content of csv to array
    var dataString = attachment.getDataAsString();
    var csvData = CSVToArray(dataString);
    // Remember to clear the content of the sheet before importing new data
    sh.clearContents().clearFormats();                                         
    //pastes array to sheet
    var lastRowValue = sh.getLastRow();
    for (var i = 0; i < csvData.length; i++) {
       sh.getRange(i+lastRowValue+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    } 
    if( message.getSubject() != 'END OF DAY SALES DETAILS' ) {
    logTodaysSales()
}
  }

  //marks the Gmail message as read, unstars it and deletes it using Gmail API (Filter sets a star)
  message.markRead();
  message.unstar();
  Gmail.Users.Messages.remove("me", message.getId()); // Added

}

//The code formats the code so it can be entered into the Google Script

function CSVToArray( strData, strDelimiter ){ 
  // Check to see if the delimiter is defined. If not,
  // then default to comma.
  strDelimiter = (strDelimiter || ",");

  // Create a regular expression to parse the CSV values.
  var objPattern = new RegExp(
    (
      // Delimiters.
      "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +


      // Quoted fields.
      "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +


      // Standard fields.
      "([^\"\\" + strDelimiter + "\\r\\n]*))"
    ),
    "gi"
  );


  // Create an array to hold our data. Give the array
  // a default empty first row.
  var arrData = [[]];

  // Create an array to hold our individual pattern
  // matching groups.
  var arrMatches = null;

  // Keep looping over the regular expression matches
  // until we can no longer find a match.
  while (arrMatches = objPattern.exec( strData )){

    // Get the delimiter that was found.
    var strMatchedDelimiter = arrMatches[ 1 ];

    // Check to see if the given delimiter has a length
    // (is not the start of string) and if it matches
    // field delimiter. If id does not, then we know
    // that this delimiter is a row delimiter.
    if (
      strMatchedDelimiter.length &&
      (strMatchedDelimiter != strDelimiter)
    ){

      // Since we have reached a new row of data,
      // add an empty row to our data array.
      arrData.push( [] );

    }

    // Now that we have our delimiter out of the way,
    // let's check to see which kind of value we
    // captured (quoted or unquoted).
    if (arrMatches[ 2 ]){

      // We found a quoted value. When we capture
      // this value, unescape any double quotes.
      var strMatchedValue = arrMatches[ 2 ].replace(
        new RegExp( "\"\"", "g" ),
        "\""
      );

    } else {

      // We found a non-quoted value.
      var strMatchedValue = arrMatches[ 3 ];

    }

    // Now that we have our value string, let's add
    // it to the data array.
    arrData[ arrData.length - 1 ].push( strMatchedValue );
  }

  // Return the parsed data.
  return( arrData );
  var label = GmailApp.getUserLabelByName("South Loop Report");
  label.deleteLabel();
}

复制数据脚本:

function logTodaysSales() {
  var todaysSales = SpreadsheetApp.getActive().getRange('Silverware-Log!SilverwareImport');
  var logSheet = todaysSales.getSheet();
  logSheet.appendRow(
    todaysSales.getValues()
    .reduce(function(a, b) { return a.concat(b); }) // flatten the 2D array to 1D
  );
}

【问题讨论】:

  • 要添加延迟,请在应用程序脚本参考文档中查找 Utilities.sleep() 函数。
  • 这对于两个脚本之间的延迟非常有效,谢谢。如果主题行包含“END OF DAY SALES DETAILS”,我也在寻找一种执行脚本的方法。

标签: google-apps-script google-sheets gmail gmail-api google-sheets-api


【解决方案1】:

使用 importCSVFromGmail 函数开头的 message 变量,您可以使用 getSubject [1] 函数获取邮件主题并将结果用于 If 条件:

if( message.getSubject() == 'END OF DAY SALES DETAILS' ) {
    //Do what you need
}

如果您想过滤主题中包含字符串“END OF DAY SALES DETAILS”的电子邮件,而不仅仅是精确匹配(如上面的那个),请在if 中使用 indexOf()[2] 函数条件:

message.getSubject().indexOf('END OF DAY SALES DETAILS') !== -1

[1]https://developers.google.com/apps-script/reference/gmail/gmail-message#getSubject()

[2]https://www.w3schools.com/jsref/jsref_indexof.asp

【讨论】:

  • 不幸的是,这似乎是在拉所有这些并每次都执行脚本,而不是只包含“END OF DAY SALES”的脚本。可能是因为主题行相似。
  • 请使用您正在使用的新代码编辑问题。可能是主题不是大写字母?必须完全匹配。
  • 使用当前脚本更新问题。不需要执行的主题行显示为:“SilverWare Insight - South Loop (Michigan Ave) - SALES DETAILS” 区分大小写。
  • 也许从附加标签中提取会更容易?在“South Loop EOD”下提交日终电子邮件
  • 所以您应该使用“SilverWare Insight - South Loop (Michigan Ave) - SALES DETAILS”而不是“END OF DAY SALES DETAILS”。是的,这是最优化的选项。
【解决方案2】:

我会稍微修改一下您的脚本以接受一条消息作为输入,并创建一个新函数来检查您的电子邮件主题。

function checkSALES() {
var thread = GmailApp.search('subject:"SALES DETAILS"', 0, 1);
var message = threads[0].getMessages()[0];
importCSVFromGmail(message)
}

function checkEndOfDay() {
var thread = GmailApp.search('subject:"SALES DETAILS"', 0, 1);
var message = threads[0].getMessages()[0];
importCSVFromGmail(message)
}


function importCSVFromGmail(message) { 
  var attachment = message.getAttachments()[0];
...

然后,我只需将每个函数的触发器设置为您希望它们运行的​​频率。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    相关资源
    最近更新 更多