0
votes

I am working on an app that needs to get a list of the recent messages in gmail by all senders in the inbox. For example I have 20 emails from "[email protected]" but I only want to fetch the last email sent by this email. I can not find any query or filter provided by google for this task. I tried fetching all emails in inbox and then process the data in the back-end, but it is a heavy work when there is a lot of emails fetched

Thank you

1
Is the address you want the mail from always going to be the same? If so, you can create a label for them and then use App Scripts to retrieve the last message. Even if it's not the same address, if you can create the label based on some pattern of the messages, you'd be able to get the last message quickly.AMolina
No unfortunately, I wanted a sort of statistic that gives all senders within an inbox. I checked gmail api reference and they don't seem to have a query of the sort. Thank you for your replyturtle

1 Answers

0
votes

Try this:

function lastEmail(){
  var userId = Session.getActiveUser().getEmail();
  var userEmail = "USER_ID";
  var optionalArgs = {
    q:userEmail
  }

  // Threads[0] will get the most recently updated thread.
  var mail = Gmail.Users.Threads.list(userId, optionalArgs).threads[0];
  Logger.log(mail);

  var message = GmailApp.getThreadById(mail.id).getMessages();
  Logger.log(message[message.length-1].getBody());
}

I played around with the API and figured a way to do what you want. You need to enable the Gmail Google Advanced Service for this to work. You can have the userEmail be retrieved from your Sheet easily working with the range you want and SpreadsheetApp. One final thing is that to get the last message of the thread (the newest one) you'll have it at message[message.length-1].