0
votes

I added a function to the menu to allow a user to click "Extract Emails" -This extracts gmails to the active pre-formatted spreadsheet The Problem: - I keep extracting the same emails... so a few things I did

1-I have a filter in Gmail that based on specific Subject 1. Stars these emails 2. Applies specific Label 2-I search for is:starred when extracting and after the loop - I remove star - I can refresh my inbox and see the stars appear and vanish 3-If I run this, and get let's say 4 emails - and run it again right away - script runs, it says finished and nothing new comes in.

HOWEVER ONCE 1 new email comes in - it stars itself, merges in that thread - If I was to again click extract emails - I'll get every email in that thread plus the new one - EVEN if the other messages in the thread are not starred

function myFunction() {

var ss = SpreadsheetApp.getActiveSheet();

var label = GmailApp.getUserLabelByName("is:starred TannerWebOppCRM");
var threads = label.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 dat = messages[j].getDate();

  ss.appendRow([msg, sub, dat])
  GmailApp.unstarMessage(messages[j]);

 }
  threads[i].removeLabel(label);
  threads[i].moveToTrash();
  }
}

I tried to move items to trash - but they aren't going. Plus when I manually moved items to the trash - they still came through.

I've read solutions for half a day and can not seem to nail the script down which will only get new messages.

In this case - once I grab the data - emails can be purged/archived/unlabeled - anything and once loaded in - I will have a time forward always.... meaning if user clicked "Get Emails" at 4 pm on Wednesday, I can start my search on email data from that point forward...

1

1 Answers

0
votes

The getUserLabelByName() method retrieves a label given the label name. It cannot be used to perform search. Also, there's no need to unstar the thread as you are moving it to trash anyway.

function myFunction() {

 var ss = SpreadsheetApp.getActiveSheet();
 var threads = GmailApp.search("is:starred in:TannerWebOppCRM");

 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 dat = messages[j].getDate();

   ss.appendRow([msg, sub, dat]);

  }

  threads[i].moveToTrash();

 }
}