Ankit Shah
Ankit Shah

Reputation: 109

Getting messages/mails sorted by date and time in Gmail API

I am working on a web app where I need to check "latest mail" that I have received from a particular sender in my gmail account on an hourly basis.

To achieve this, I used the Gmail API for PHP and was able to retrieve mails from a particular sender but I need to sort this mails/messages w.r.t date and time so that I can get the last email from a particular sender.

I checked Advanced Search options of Gmail API which provides to sort with respect to date , however it doesn't provide any method to handle it with respect to time.

Is there any way to get the time and date and sort it? or any other approach that can help me get the "latest" mail from a particular sender?

Please help me out. Thanks in Advance.

Upvotes: 7

Views: 5031

Answers (2)

André Peregrina
André Peregrina

Reputation: 313

This question is from too old but if someone is looking for something similar you can use the after: in the q parameter to ask for the listed emails by hour. The only thing you have to do is send how many seconds before of the current time.

Example:

gmail.users.messages.list({
      userId: 'me',
      q: `-in:chats is:unread newer_than:1d after:${tenMinutesBefore.unix()}`
}, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
   const messages = res.data.messages; // Messages from an hour ago to now
});

Upvotes: 0

Tholle
Tholle

Reputation: 112787

You could just list the messages, asking for a single message and explicitly saying what email address it should be from.

maxResults = 1
query = from:[email protected]

GET https://www.googleapis.com/gmail/v1/users/me/messages?maxResults=1&q=from%3Aexample%40gmail.com&access_token={YOUR_API_KEY}

Response:

{
 "messages": [
  {
   "id": "14e97f7ea9b794a4", // This is the Id of the latest message.
   "threadId": "14e97f7ea9b794a4"
  }
 ],
 "nextPageToken": "03176727664356668776",
 "resultSizeEstimate": 3
}

Now it's just a matter of getting the message! If you are interested in when the user received the mail, you can ask for the internalDate, which represents time in ms since the epoch that the message got created.

fields = internalDate,payload/body/data

GET https://www.googleapis.com/gmail/v1/users/me/messages/14e97f7ea9b794a4?fields=internalDate%2Cpayload%2Fbody%2Fdata&access_token={YOUR_API_KEY}

Response:

{
 "internalDate": "1437068683000", // This is when the message was created.
 "payload": {
  "body": {
   "data": "VGhlIGFjdHVhbCBtZXNzYWdlIHRleHQgZ29lcyBoZXJl" // This is the mail data.
  }
 }
}

This is not php code, but you know that better than me! Just use the same queries and fields in your framework, and you will get the same result.

Upvotes: 0

Related Questions