Search code examples
google-apps-scriptgmail

How to delete thread messages in row via Google Apps Script?


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


Solution

  • Modification points:

    • In your script, the email moved to the trash can still be retrieved with 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.
    • If you want to use 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.

    Modified script:

    From:

    var message = thread.getMessages()[0]; // Get the latest message
    
    ogger.log('zero'+thread.getMessages()[0].getPlainBody());
    message.moveToTrash()
    

    To:

    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;
    }
    
    • By this modification, the message is moved to the trash every run.

    Sample script:

    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());
    }
    
    • This script deletes the thread. So when you test this, please test the script using the sample thread. Please be careful this.

    References: