简体   繁体   中英

Google Apps Script, GMail, Spreadsheets

What I'm trying to achieve: Pull emails from gmail account as they come in that match a particular criteria "subject:contains this text" within label "label/sub label", and appends the subject of that email to column D and the timestamp from when that mail was received into column B.

What I have so far: it can pick the most recent emails (set to 5 as an example) and append to column A.

   function parseEmailMessages(start) {

      start = start || 0;

      var threads = GmailApp.getUserLabelByName('Label/SubLabel').getThreads(start, 5);
      var sheet = SpreadsheetApp.getActiveSheet();

      for (var i = 0; i < threads.length; i++) {

        // Get the first email message of a threads
        var tmp,
          message = threads[i].getMessages()[0],
          subject = message.getSubject(),
          content = message.getPlainBody();

        // Get the plain text body of the email message
        // You may also use getRawContent() for parsing HTML

        // Implement Parsing rules using regular expressions
        if (content) {

          tmp = content.match(/Name:\s*([A-Za-z0-9\s]+)(\r?\n)/);
          var username = (tmp && tmp[1]) ? tmp[1].trim() : 'No username';

          tmp = content.match(/Email:\s*([A-Za-z0-9@.]+)/);
          var email = (tmp && tmp[1]) ? tmp[1].trim() : 'No email';

          tmp = content.match(/Comments:\s*([\s\S]+)/);
          var comment = (tmp && tmp[1]) ? tmp[1] : 'No comment';

          sheet.getRange(sheet.getLastRow(), 3).setValues(test);
          //sheet.appendRow([subject]);

        } // End if

      } // End for loop
    }

You should modify the way you are fetching threads from Gmail:

  var threads = GmailApp.getUserLabelByName('Label/SubLabel').getThreads(start, 5);

change this to:

  var threads = GmailApp.search('subject:(contains this text) label:Label-SubLabel', start, 5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM