Reputation: 13
I am trying to search in my Inbox for mails that are newer than 10 minutes with Apps Script.
Background: I am triggering to send a xlsx from sheets to a certain person every 2 hours. They are updating the list and send it back to me. Now I want to grab the updated file and upload it again to sheets to update the original file accordingly.The script works well enough to take the attachment and upload it as sheets to my drive. My problem: It seems to grab the file that was originally triggered instead of the new updated file that is sent back to me (therefore the updates from the new file are missing).
I tried to add different "search queries" within GmailApp.search but it doesn't seem to work for me:
var threads = GmailApp.search("newer_than:0.1h AND from:mail.com AND subject:Issue Log AND -label:processed AND -in:sent",0,10);
I tried "newer_than:0.1h" but that seems to be incorrect. Any idea if searching for mails that are max 10 minutes old would help? Any other suggetions that I might do wrong here? I am running out of ideas really...
Thanks in advance!
Upvotes: 1
Views: 2415
Reputation: 1461
I think your problem is that you are not handling the messages within a thread properly. I'm attaching another piece of code so that you can get every message in a thread and its information such as the subject, body and attachments. This way you can find the file you need.
for (var i = 0; i < threads.length; i++) {
messages = threads[i].getMessages()
for (var j = 0; j < messages.length; j++) {
subject = messages[j].getSubject()
body = messages[j].getPlainBody()
attachment = messages[j].getAttachments()
}
}
Upvotes: 0
Reputation: 1461
I think that your problem needs a different approach to get the emails that you want. However, regarding the main question that you present, it is currently not possible to get the messages newer than 10 minutes. You can find all the information about search operators here.
Although the official documentation says Search for messages older or newer than a time period using d (day), m (month), and y (year)
you can also use h(hour)
in your search, but keep in mind that these values have to be an integer.
However, there is a workaround if you really need to work with small time differences. You can compare the current time with the time of each message. I let you a small piece of code so you can see better.
var threads = GmailApp.search("newer_than:1d") // change that query for the one that works for you
var now = new Date() // current time
for (var i = 0; i < threads.length; i++) {
message = threads[i].getMessages()[0]
time = message.getDate()
subject = message.getSubject()
diff = (now-time)/60000 // milliseconds to minutes
Logger.log('Message with subject ' + subject + ' has been received ' + diff + ' minutes ago');
}
Anyway, you should be able to get the messages that you need just using proper search operators regardless of the time period related.
Upvotes: 3