【发布时间】:2018-02-13 01:46:51
【问题描述】:
我正在尝试使用 gmail api 将过滤器应用到我的收件箱。我只能看到创建标签的支持。您能帮我了解如何创建过滤器并为与过滤器匹配的电子邮件应用标签吗?
感谢您的帮助
【问题讨论】:
标签: gmail-api
我正在尝试使用 gmail api 将过滤器应用到我的收件箱。我只能看到创建标签的支持。您能帮我了解如何创建过滤器并为与过滤器匹配的电子邮件应用标签吗?
感谢您的帮助
【问题讨论】:
标签: gmail-api
过滤条件描述搜索查询。可以获取与该搜索查询匹配的所有线程并执行过滤器的效果。
我这里有一个简单的例子。如果主题匹配字符串,我们使用一个简单的过滤器添加标签。这个例子可以扩展到涵盖任意过滤器。
正如@Tholle 提到的,我也找不到简单的“对现有消息运行此过滤器”api 调用。
def createFilter(service,userId,o):
r = service.users().settings().filters().create(
userId=userId,body=o).execute()
print("Created filter {}".format(r.get("id")))
return r
def getMatchingThreads(service,userId,labelIds,query):
"""Get all threads from gmail that match the query"""
response = service.users().threads().list(userId=userId,labelIds=labelIds,
q=query).execute()
threads = []
if 'threads' in response:
threads.extend(response['threads'])
# Do the response while there is a next page to receive.
while 'nextPageToken' in response:
pageToken = response['nextPageToken']
response = service.users().threads().list(
userId=userId,
labelIds=labelIds,
q=query,
pageToken=pageToken).execute()
threads.extend(response['threads'])
return threads
def buildSearchQuery(criteria):
"""Input is the criteria in a filter object. Iterate over it and return a
gmail query string that can be used for thread search"""
queryList = []
positiveStringKeys = ["from","to","subject"]
for k in positiveStringKeys:
v = criteria.get(k)
if v is not None:
queryList.append("("+k+":"+v+")")
v = criteria.get("query")
if v is not None:
queryList.append("("+v+")")
# TODO: This can be extended to include other queries. Negated queries,
# non-string queries
return " AND ".join(queryList)
def applyFilterToMatchingThreads(service,userId,filterObject):
"""After creating the filter we want to apply it to all matching threads
This function searches all threads with the criteria and appends the same
label of the filter"""
query = buildSearchQuery(filterObject["criteria"])
threads = getMatchingThreads(service,userId,[],query)
addLabels = filterObject["action"]["addLabelIds"]
print("Adding labels {} to {} threads".format(addLabels,len(threads)))
for t in threads:
body = {
"addLabelIds": addLabels,
"removeLabelIds": []
}
service.users().threads().modify(userId=userId,id=t["id"],
body=body).execute()
# Create your service like in here
# https://developers.google.com/gmail/api/quickstart/python
desiredFilters = [
{
"criteria": {
"subject": "[JIRA]",
},
"action": {
"addLabelIds": [labelNameToId["jira"]],
}
},
]
for df in desiredFilters:
createFilter(service,"me",df)
applyFilterToMatchingThreads(service,"me",df)
这不是一个完整的按钮工作示例。您需要先创建自己的服务对象并进行 OAUTH2 身份验证。
【讨论】:
您不能使用 Gmail API 将过滤器应用到收件箱。 Gmail API 提供对草稿、历史记录、标签、消息、附件、线程的 RESTful 访问权限以及查看邮箱以接收推送通知的能力。
【讨论】: