2
votes

Is there a way to list Gmail mails using Google Mail APIs in sorted order of receive time?

Although the API returns the mails in reverse chronological order. For a very small data set like 10 mails, I am finding a discrepancy.

Response of mail list API:

 {
 "messages": [
  {
   "id": "15afb61b8d220a19",
   "threadId": "15afb61b8d220a19"
  },
  {
   "id": "15afb618f941d73f",
   "threadId": "15afb618f941d73f"
  },
  {
   "id": "15afb6174711c7af",
   "threadId": "15afb6174711c7af"
  },

  ...
  ...
  {
   "id": "159bc283f63d5eb7",
   "threadId": "159bc283f63d5eb7"
  },
  {
   "id": "159bc283dc97cd87",
   "threadId": "159bc283dc97cd87"
  },
  {
   "id": "159bc283d95f097c",
   "threadId": "159bc283d95f097c"
  }
 ],
 "resultSizeEstimate": 9
}

First message in response(most recent):

Id: 15afb61b8d220a19
Date: "Thu, 23 Mar 2017 19:06:08 +0530" 
internalDate: "1490276168000"

Second mail in list:

Id: 15afb618f941d73f
Date: "Thu, 23 Mar 2017 19:05:58 +0530"
internalDate: "1490276158000"

... ... Second last mail in the list:

Id: 159bc283dc97cd87 
Date: "Fri, 20 Jan 2017 05:54:30 -0800" 
internalDate: "1484920470000"

Last mail in the list(should be oldest, but is not):

Id: 159bc283d95f097c
Date: "Fri, 20 Jan 2017 05:54:31 -0800"
internalDate: "1484920471000"
2

2 Answers

2
votes

I guess it's the expected behavior based from this thread.

...messages.list does NOT return in date ASC or date DESC. They are returned randomly as far as I can tell.

You can also use the search syntax to filter by email's date.

-1
votes

Seems like a parameter that should be offered but apparently not. Still, it's pretty easy to sort results youself.

If you are using php you can use usort(). First build an array of messages from your list with internalDate as a key (looks like you've done that). If you wanted them in descending order:

usort($messages, function($a, $b) {
    return $b['internalDate'] <=> $a['internalDate'];
});