【发布时间】:2021-01-13 12:41:36
【问题描述】:
我将 Gmail 的 API 用于 Python 3 项目。该项目涉及输入多个过滤器,以便程序在符合多个条件的新电子邮件进入时进行报告。这是我正在使用的参考链接:http://googleapis.github.io/google-api-python-client/docs/dyn/gmail_v1.html。
该引用表明,在service.users().messages().list() 方法中,您可以指定一个参数q,它是一个查询字符串,其功能与Gmail 中的搜索栏相同。 (意思是,您应该能够输入from:sample@example.com is:unread,并从 sample@example.com 中取回未读的电子邮件。但是,当我尝试使用刚刚发送到的电子邮件执行此操作时我自己,我得到了 0 个结果。
这是我正在做的事情:
results = service.users().messages().list(userId='me', q='from:sample@example.com is:unread').execute()
这会返回 0 个结果,尽管我可以清楚地在我的电子邮件中看到与此确切条件匹配的电子邮件,并且当我尝试使用具有完全相同查询的搜索栏时,电子邮件会按原样返回。我也尝试对日期进行此操作,虽然它适用于 Gmail 搜索栏,但不适用于 API。
results = service.users().messages().list(userId='me', q='from:sample@example.com after:09/26/2020').execute()
似乎也没有“AND”运算符,但是有一个“OR”运算符,这不是我想要的。有没有其他人经历过这个?如果是这样,有什么方法可以解决这个问题?我意识到这可以在没有 Gmail API 的情况下完成,但这个项目的目的是使用 API。
编辑:如果有帮助,这里是服务对象的定义方式,在他们网站上的 quickstart.py 中提供。
SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
def get_service():
"""
Create a service object for Gmail api. (Gmail-defined code)
"""
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
print('Service successfully acquired')
return service
上面sn-ps中引用的服务对象是通过输入创建的:
service = get_service()
编辑 2:我不知道这是否对这个问题有任何启示,但我尝试过的这个查询返回结果,而其他具有多个参数的查询不会返回任何内容。
message_list = service.users().messages().list(userId='me', q='in:inbox is:unread').execute()
【问题讨论】:
-
Gmail aAPI 的
q参数的工作方式与 UI 中的完全一样。from:sample@example.com is:unread是一个有效的查询。使用Try this API 对其进行测试(确保不要将查询字符串放在引号中)。 -
感谢您的回复,并且我已经测试了测试 UI(效果很好),但这不是我想要使用的 - 我正在尝试使用他们的 Python 客户端库,它我在帖子的第一段中链接了 - 无论出于何种原因,当文档声称时,q 参数(应该是一个字符串,意味着它需要用引号引起来)不允许传递多个参数它应该。
-
我对您链接的批处理请求方法感到困惑。你是怎么定义
service的? -
服务是使用他们在页面上运行的 quickstart.py 中的方法定义的。如果有帮助,我会将其添加到原始帖子中。
-
我刚刚测试了以下请求,它对我来说没有问题:` results = service.users().messages().list(userId='me', q='from:sample@ example.com is:unread').execute() emails = results.get('messages', []) print('mails:') for email in emails: print(email['id'])` 你确定您有符合查询条件的消息吗?
标签: python-3.x gmail-api