【问题标题】:Applying filters using gmail api使用 gmail api 应用过滤器
【发布时间】:2018-02-13 01:46:51
【问题描述】:

我正在尝试使用 gmail api 将过滤器应用到我的收件箱。我只能看到创建标签的支持。您能帮我了解如何创建过滤器并为与过滤器匹配的电子邮件应用标签吗?

感谢您的帮助

【问题讨论】:

    标签: gmail-api


    【解决方案1】:

    过滤条件描述搜索查询。可以获取与该搜索查询匹配的所有线程并执行过滤器的效果。

    我这里有一个简单的例子。如果主题匹配字符串,我们使用一个简单的过滤器添加标签。这个例子可以扩展到涵盖任意过滤器。

    正如@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 身份验证。

    【讨论】:

      【解决方案2】:

      您不能使用 Gmail API 将过滤器应用到收件箱。 Gmail API 提供对草稿、历史记录、标签、消息、附件、线程的 RESTful 访问权限以及查看邮箱以接收推送通知的能力。

      您可以create filters with the admin sdk

      【讨论】:

      • 我试过了,但看起来 ClientLogin 已被弃用 developers.google.com/identity/protocols/AuthForInstalledApps
      • @Noobdev 我猜 ClientLogin 已被弃用,但可以通过 Gmail API 创建过滤器。是否仍然无法通过 Gmail API“应用”/“运行”过滤器?我希望在过滤器创建 GUI 中实现与“也将过滤器应用于匹配的对话”选择相同的功能。
      • @Noobdev 我想人们也可以通过 GUI 和append the right labels 以编程方式执行过滤器中定义的相同搜索。
      猜你喜欢
      • 2016-12-22
      • 2021-10-12
      • 2016-10-24
      • 2018-08-17
      • 2016-07-22
      • 2021-11-20
      • 2018-10-12
      • 2014-10-15
      • 1970-01-01
      相关资源
      最近更新 更多