Feature request:- Implement orderBy in query sensor
Was very pleased to get this integration up and running - with the new 2FA methods using the IMAP email sensor is not an option for me, and this one works so well.
I was wondering how complex it would be to include the orderBy clause in the query sensor configuration? I'm not a python coder, but it looks like this is implemented in the python-o365 package so hopefully a minor change on this end.
My use case is I've got a flow in Node red that triggers on boot or when a new email matching a subject arrives. Extracting a word from the body of the email I can then set a binary sensor to the appropriate state. I only want to return a single email (max_items: 1), and I don't care if it's read or unread (again easy to do with the options). However, I've not got a choice over which order it returns them in, and by default it appears to be returning the oldest email first when I really need the newest.
I can do a temporary workaround by returning more items and then using a function to find the newest, but would be much cleaner if I could use the full power of the odata query parameters to only return the email of interest.
Makes sense. The default order should actually probably have been newest first. I will look into this when I have a moment
I had a crack at this myself and eventually got something that worked but the code isn't pretty so haven't developed into a PR. I changed the update action to:
self.mail_folder.get_messages(
limit=self.max_items, query=self.query, order_by='receivedDateTime desc', download_attachments=True
)
However, what tripped me up for ages was that you need to have 'receivedDateTime' included as a filter too if you want to use it in the orderBy clause: https://developer.microsoft.com/en-us/office/blogs/update-to-filtering-and-sorting-rest-api/
I added these two lines below the conf.get statements and before it starts appending the query clauses:
self.query = self.mail_folder.new_query()
self.query.on_attribute("receivedDateTime").greater_equal(dt.datetime(2010, 1, 1))
This is far from pretty (a datetime of 2010 or newer was fine for me) but works so my email query sensor now always returns the latest message first.