简体   繁体   English

如果 gmail 主题包含“ ”,如何运行脚本

[英]How to run script if gmail subject contains “ ”

I have a script that imports CSV gmail attachments to google sheets, it runs every minute.我有一个脚本将 CSV gmail 附件导入到谷歌表格,它每分钟运行一次。 I have another script that copies data to another sheet, I'd like to include the copy script to run after the import CSV script IF the email Subject line contains "END OF DAY SALES DETAILS".我有另一个将数据复制到另一个工作表的脚本, IF email 主题行包含“一天结束的销售详情”,我想包括在导入 CSV 脚本之后运行的复制脚本。 This happens once per day, throughout the day the Subject line contains "SALES DETAILS".这每天发生一次,全天主题行包含“销售详情”。

Would need a small delay after importing CSV to ensure everything was fully processed, will achieve with Utilities.sleep() If Subject line contains the expected string.导入 CSV 以确保所有内容都已完全处理后,将需要一点延迟,如果主题行包含预期的字符串,将使用Utilities.sleep()实现。

Import CSV script:导入 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();
}

Copy data script:复制数据脚本:

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
  );
}

With the message variable you have at the beginning of the importCSVFromGmail function, you can get the message subject with getSubject [1] function and use the result in an If condition:使用 importCSVFromGmail function 开头的消息变量,您可以使用 getSubject [1] function 获取消息主题,并将结果用于 If 条件:

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

If you want to filter the emails that include the string 'END OF DAY SALES DETAILS' in their subject and not only the exact matches (Like the one above), use indexOf()[2] function in the if condition:如果您想过滤主题中包含字符串“END OF DAY SALES DETAILS”的电子邮件,而不仅仅是完全匹配的邮件(如上面的那个),请在if条件中使用 indexOf()[2] function:

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

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

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

I would change your script a little bit to accept a message as an input and create a new function to check on your email subjects.我会稍微更改您的脚本以接受一条消息作为输入并创建一个新的 function 来检查您的 email 主题。

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];
...

Then I would just set the triggers on each function at the frequency you want them to run at.然后我会以您希望它们运行的频率设置每个 function 上的触发器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 label 电子邮件的脚本,如果它在 Gmail 的主题或正文中包含特定单词 - Script to label emails if it contains specific words in the subject or body on Gmail Google脚本按主题过滤Gmail自动回复 - Google Script Filter by Subject for Gmail Auto Reply 如何在多个 gmail 日历上运行脚本 - How to run a script on several gmail calendars 使用 App-Script 从 Gmail 中的标签名称使用 getThreads() 时,如何防止按主题或日期分组? - How to prevent grouping by subject or date when using getThreads() from a label name in Gmail using App-Script? 如何使用电子表格中的 Google App 脚本生成 Gmail 草案包含正文中的表格 - How to Generate Gmail draft using Google App Script from Spreadsheet contains Table in the Body 更改Gmail主题行 - Alter the gmail subject line 如何从Gmail获取主题并将其放入Google文档或电子表格 - How to get subject from gmail and put into a google doc or spreadsheet 如何将浏览器选项卡更改为 gmail 的当前 email 主题 - How to change browser tab to current email subject for gmail 如何获得 email gmail python ZDB974238714CA8DE634A7CE1D083A14 的主题 - How can I get the subject of an email gmail python API 如何从 Google 表格动态向 Gmail 主题提供价值? - How to dynamically feed value to Gmail subject from Google Sheets?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM