1

First off: JavaScript novice. Any help/direction you could provide would be greatly appreciated.

I have a new business case in which a GMail box is going to receive an e-mail 4 times a day with the same subject line, but with a new .csv attachment each time. I've created the label within GMail, and it is attaching successfully to each email. I need to be able to use Apps Script to only process the oldest unread e-mail. The part to parse the .csv is already tested/successful/completed. However, each time I run it, it's looping through all the files, and processing them again.

Here is the current code for getting information from the GMail Box

// GMail Details
var gmailLabel = ('_Projects/ProjectLabel');
var label = GmailApp.getUserLabelByName(gmailLabel);
var unreadCount = label.getUnreadCount();
var gmailThreads = GmailApp.getUserLabelByName(gmailLabel).getThreads();
Logger.log(label.getUnreadCount());
  for (var i = 0; i < gmailThreads.length; i++) {
   Logger.log(gmailThreads[i].getFirstMessageSubject());
  }
}

The log does show that there are 2 unread threads correctly, and does display the subject line in the logger. However, within the gmailThreads array, I can only see the object numbers for the threads. How could I get object numbers for each of the e-mails belonging to those threads? This would be the e-mail that I would need to parse the .csv attachment first, then mark as read (or change the label of) within the loop.

Thanks again for looking!

Steve Wolfe
  • 85
  • 1
  • 1
  • 7

1 Answers1

0

To get the IDs of the first messages in a given Gmail Thread, you need to call getMessages() to retrieve all the messages, and then access the first message in the resulting array, with [0]:

var firstMessage = thread.getMessages()[0];

Then you can do a number of things with this GmailMessage, such as retrieve its ID (.getId()) or attachments (.getAttachments()).

tehhowch
  • 9,645
  • 4
  • 24
  • 42
  • Ok, great. I think I got it. I need to find all threads, the iterate through them to get each ID. Inside that loop, once complete, would it be best practice to change the label or remove from thread so it doesn't try processing agian? – Steve Wolfe Apr 16 '18 at 17:32
  • @SteveWolfe Yep, to avoid re-processing the thread in a subsequent call, you'll want to modify the message such that it no longer matches your function's query. Currently, you query for a given label and the "unread" property. You could mark the message read, remove the searched label, add a new label after processing (and update your query to require the first label and also the absence of the 2nd), etc. – tehhowch Apr 16 '18 at 17:46