title: Python Gmail API. Search for emails based on Labels and Ascending Time Order?
body: <p>I am using the Gmail API with Python. I would like to search for email messages using a label, in time ascending order. I am able to search for emails using a label or list of labels with the following function:</p>
  <pre class="lang-py prettyprint-override"><code>def gmailAPIMessageLabelSearch(self, labelList, userID=&quot;me&quot;, allPages=False):
      try:
          self.GLogger.info(&quot;Attempting to search emails with labelList (&quot; + str(labelList)+ &quot;) and userID (&quot; +str(userID)+ &quot;)&quot;)
          service = self.gmailAPIService
          if service is None:
              logging.error('Gmail Service not initialized')
              return False
          response = service.users().messages().list(userId=userID, labelIds=labelList).execute()
          messages = []
          if 'messages' in response:
              messages.extend(response['messages'])
          if allPages is True:     
              while 'nextPageToken' in response:
                  page_token = response['nextPageToken']
                  response = service.users().messages().list(userId=userID, labelIds=labelList, pageToken=page_token).execute()
                  if 'messages' in response:
                      messages.extend(response['messages'])
          self.GLogger.info(&quot;Successfully searched emails with labelList (&quot; + str(labelList)+ &quot;) and userID (&quot; +str(userID)+ &quot;). Number of matching emails (&quot; +str(len(messages))+ &quot;)&quot;)
          return messages
      except:
          self.GLogger.error(&quot;An error was encounrtered while searching for messages with google API and label list&quot;)
          tb = traceback.format_exc()
          self.GLogger.exception(tb)
          return False
  </code></pre>
  <p>However, I would specifically like to ensure that I am receiving emails in Time Ascending Order. So the search should return with the oldest first and newest last.</p>
  <p>Also, I am not able to simply download the emails and then sort. The emails are used in real time, so they cannot be stored and then sorted. I am aware it would be possible to simply download the emails and then extract their time and sort accordingly. However, this is not an option. I would need the results of the search to already provide this list in ascending time order.</p>
  <p>Is there a way of doing this?</p>
  <p>I tried searching and checking the Gmail API for the list() function but I don't see a way. I tried applying &quot;Oldest&quot; label, and didn't do anything.</p>