Reputation: 13
I try to write function which would delete message in Gmail thread with several messages.
function movetotrash()
{
var thread = GmailApp.getInboxThreads(0,1)[0]; // Get first thread in inbox
if (thread==null)
{}
else
{
var message = thread.getMessages()[0]; // Get the latest message
Logger.log('zero'+thread.getMessages()[0].getPlainBody());
message.moveToTrash()
}
}
I can see that message disappeared in gmail interface. But when I call this function again I can see that message [0] is the same
Upvotes: 1
Views: 887
Reputation: 59
Use isInTrash() on each message.
function movetotrash()
{
var thread = GmailApp.getInboxThreads(0,1)[0]; // Get first thread in inbox
if (thread==null)
{}
else
{
i=0
while (thread.getMessages()[i].isInTrash()) i++
var message = thread.getMessages()[i]; // Get the latest not in trash message
Logger.log('zero'+thread.getMessages()[i].getPlainBody());
message.moveToTrash()
}
}
Upvotes: 0
Reputation: 201553
var message = thread.getMessages()[0]
. By this, after you run the script, you can retrieve the same message with var message = thread.getMessages()[0]
. I thought that this might be the reason of your issue.moveToTrash()
, how about checking whether the email is in the trash? In this case, you can use isInTrash()
.When the above points are reflected in your script, it becomes as follows.
var message = thread.getMessages()[0]; // Get the latest message
ogger.log('zero'+thread.getMessages()[0].getPlainBody());
message.moveToTrash()
var messages = thread.getMessages();
for (var i = 0; i < messages.length; i++) {
if (messages[i].isInTrash()) continue;
Logger.log(messages[i].getPlainBody());
messages[i].moveToTrash();
break;
}
From your title of How to delete thread messages in row via Google Apps Script?
, if you want to delete all messages of the thread, you can also use the following script.
Before you use this script, please enable Gmail API at Advanced Google services.
var thread = GmailApp.getInboxThreads(0, 1)[0]; // Get first thread in inbox
if (thread) {
Gmail.Users.Threads.remove("me", thread.getId());
}
Upvotes: 1