0
votes

I like to record an email's Subject/Sender/Date/ID into a spreadsheet by it's label and add a "Recorded" label to the email once it's recorded into the spreadsheet. I like to run the script again without re-recording emails with the label "Recorded"

I can get it to the point of recording to spreadsheet and adding the label. but everything i run the script it grabs everything again.

function myFunction() {

  var ss = SpreadsheetApp.getActiveSheet();
  var searchlabel = GmailApp.getUserLabelByName("Test");
  var newlabel = GmailApp.getUserLabelByName("Recored");
  var threads = searchlabel.getThreads();

  for (var i=0; i<threads.length; i++)
  {
    var messages = threads[i].getMessages();

    for (var j=0; j<messages.length; j++)
    {
      var msg = messages[j].getBody();
      var sub = messages[j].getSubject();
      var from = messages[j].getFrom();
      var dat = messages[j].getDate();
      var id = messages[j].getId();
      var current = new Date();

      ss.appendRow([current, dat, sub, id, from])
    }
      threads[i].addLabel(newlabel);
  }
}

I've search the forum and everything tends to suggest to remove the existing label and rename to a different label. But what i wantenter code here is to keep the existing label.

2

2 Answers

0
votes

You can try replacing var threads with:

var threads = GmailApp.search('label:(Test -Recored)');

This searches for all labels with Test but not Recored.
You wouldn't need var searchlabel anymore.

0
votes

You should the search method since it lets you filter emails that belong to a particular label. Here's the modified version.

function myFunction() {

  var ss = SpreadsheetApp.getActiveSheet();
  var searchlabel = GmailApp.getUserLabelByName("Test");
  var recordlabel = GmailApp.getUserLabelByName("Recorded"); 
  var threads = GmailApp.search("label:Test -label:Recorded");

  for (var i=0; i<threads.length; i++)
  { 
    var messages = threads[i].getMessages();

    for (var j=0; j<messages.length; j++)
    {
      var msg = messages[j].getBody();
      var sub = messages[j].getSubject();
      var from = messages[j].getFrom();
      var dat = messages[j].getDate();
      var id = messages[j].getId();
      var current = new Date();

      ss.appendRow([current, dat, sub, id, from])
    }
      threads[i].addLabel(recordlabel);
  }
}