I have an automation script that handles emails with a particular subject. It was working for a while, but now there is a second type of email that gets the same label and has a very similar subject. The subject I want is RITM12345 Approval Request where 12345 can be any number. The subject I don't want is CHG12345 Approval Request where 12345 can be any number.
I wanted to initially put a regular expression inside the GmailApp.search function, but the regex is taken as a literal string. I can't seem to find any documentation on how to filter this during the email search. I tried GmailApp.search('subject:"Approval Request"-CHG'), but this does not work because the rest of the CHG string has numbers appended to it.
Currently, I am doing this:
var threadSubject = /RITM([0-9]+) Approval Request/;
var threads = GmailApp.search('from:"email.com" is:unread subject: "Approval Request" label:"Approval Request"', 0,1);
if (threads.length > 0) {
for (var i=0; i < 1; i++) {
var messages = GmailApp.getMessagesForThread(threads[i]);
for (var j=0; j < messages.length; j++ ) {
var message = threads[i].getMessages()[j];
var subject = message.getSubject();
}
if (subject.match(threadSubject)) {
do automation code here if it matches my regex, then mark thread as read
}
The code re-runs in a minute and finds next unread message
The inherent problem with this code is that I only want to find unread messages with the desired subject. Currently, this code is only locating the unread CHG12345 Approval Request thread over and over again (since it is the first thread found). Marking this unwanted thread read or changing this unwanted threads label are also not an option.
Also, one other thing to note. I am only grabbing one email at a time in my loop and the script triggers every minute. This is done for logging reasons and I was also getting bugs when the script would try to handle 20+ emails all at once