我正在尝试使用gmail api将过滤器应用到我的收件箱中。我只能看到创建标签的支持。你能帮我理解如何创建过滤器并为与过滤器匹配的电子邮件应用标签吗?
感谢您的帮助
答案 0 :(得分:1)
您无法使用Gmail API将过滤器应用于收件箱。 Gmail API提供对草稿,历史记录,标签,邮件,附件,线程的RESTful访问权限以及观看邮箱以接收推送通知的功能。
答案 1 :(得分:0)
过滤条件描述了搜索查询。可以使所有线程匹配该搜索查询并执行过滤器的效果。
我在这里有一个简单的例子。我们使用一个简单的过滤器,如果主题与字符串匹配,则添加标签。可以扩展此示例以涵盖任意过滤器。
正如@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身份验证。