google-apps-scriptgmail-api

How to get the most recent Gmail message in Google Apps Script?


The docs are thin.

Using GAS, how do I get the most recent Gmail message in my inbox matching a specific subject string?

function getConfig() {
  var email = {
    subject: 'My subject string', 
  };
  email.q = [
    [ 'label'   , 'inbox'       , ].join(':'),
    [ 'subject' , email.subject , ].join(':'),
  ].join(' ');
  var config = {
    me: 'me',
    email: email
  };
  return config;
}

function getMessages() {
  var config = getConfig();
  var me = config.me;
  var email = config.email;
  var q = email.q;
  var msgs = Gmail.Users.Messages.list(me, {
    q: q,
  });
  Logger.log('Messages length: %s', msgs.length); // undefined
}

As you can see, the logger returns undefined.


Solution

  • You can use GmailApp to get the Messages. It will return you data in an array and you can easily sort it.

    Also, you can search the messages by passing a specific query.

    Document Link

    Hope it helps!.