Python Gmail API.根据标签和升序搜索电子邮件



我使用的是带有Python的Gmail API。我想使用标签搜索电子邮件,按时间升序排列。我可以通过以下功能使用标签或标签列表搜索电子邮件:

def gmailAPIMessageLabelSearch(self, labelList, userID="me", allPages=False):
try:
self.GLogger.info("Attempting to search emails with labelList (" + str(labelList)+ ") and userID (" +str(userID)+ ")")
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("Successfully searched emails with labelList (" + str(labelList)+ ") and userID (" +str(userID)+ "). Number of matching emails (" +str(len(messages))+ ")")
return messages
except:
self.GLogger.error("An error was encounrtered while searching for messages with google API and label list")
tb = traceback.format_exc()
self.GLogger.exception(tb)
return False

然而,我特别想确保我收到的电子邮件是按时间升序排列的。因此,搜索应该返回最古老的第一个和最新的最后一个。

此外,我不能简单地下载电子邮件然后进行排序。这些电子邮件是实时使用的,因此无法存储并进行排序。我知道可以简单地下载电子邮件,然后提取它们的时间并进行相应的排序。然而,这不是一种选择。我需要搜索的结果已经提供了这个列表的升序时间。

有办法做到这一点吗?

我试着在Gmail API中搜索和检查list((函数,但我看不到任何方法。我试着申请";最旧的";标签,什么也没做。

由于谷歌邮件不提供反转排序的功能,最简单的方法是使用列表检索第一页,然后响应包括对结果总数resultSizeEstimate的估计,基于此,您可以跳到最后一页,然后只需对该页的电子邮件进行排序。

文档表示q参数支持与Gmail搜索框相同的查询格式。

请参阅此处,了解它接受哪些条款:https://support.google.com/mail/answer/7190?hl=en其中一些术语对于筛选消息非常有用。

最新更新