Search code examples
javascriptgoogle-apps-scriptfiltergmail

Manage Filter ID Gmail


I am trying to create a filter for every people's email in a group. However, sometimes the a person's email can changes like adding new email or change to another mail email. That means I have to update the filter accordingly. I tried to create filter with ID that with the person's name. So I can retrieve that filter to modify it. However, it seems that the Gmail filter's ID are created automatically.

var filter = Gmail.newFilter()
var email = '[email protected]'
filter.id = 'person'
filter.criteria = Gmail.newFilterCriteria()
filter.criteria.query = email
filter.action = Gmail.newFilterAction()
filter.action.addLabelIds = ['Label_1']
Gmail.Users.Settings.Filters.create(filter, 'me')  

When I get back the filter, it will say that it cannot be found

var filter2 = Gmail.Users.Settings.Filters.get('me', 'person')

This will return Not Found error even I can see the filter in setting in my Gmail. The actually ID for the filter I created above is ANe1Bmgel8OKlEXD-uArX77ISk35Lph1MbWWjA.

My question is what's the good way to manager filters through changes, keep them updated?


Solution

  • Per the API documentation for a Filter resource:

    id: string The server assigned ID of the filter.

    Thus, you cannot assign the ID, and any value you set for it in the call to .create is ignored.

    You can still programmatically retrieve this filter, using .list and Array#filter, e.g.

    function getAllFilters_(userId) {
      const options = {};
      const filters = [];
      do {
        var search = Gmail.Users.Settings.Filters.list(userId, options);
        if (search.filter && search.filter.length) {
          Array.prototype.push.apply(filters, search.filter);
        options.pageToken = search.nextPageToken;
      } while (options.pageToken);
      return filters;
    }
    function getFiltersWithCriteria_(filterList, criteria) {
      // `criteria` is an object of parameters that must be exactly matched in the filters' criteria property
      const props = Object.keys(criteria);
      const matches = filterList.filter(function (gFilter) {
        // gFilter is a https://developers.google.com/gmail/api/v1/reference/users/settings/filters#resource
        var fCriteria = gFilter.criteria;
        return props.every(function (prop) {
          return criteria[prop] === fCriteria[prop];
        });
      });
      return matches;
    }
    function foo() {
      const filters = getAllFilters_("me");
      const matched = getFiltersWithCriteria_(filters, {
        from: "[email protected]",
        hasAttachment: true
      });
      console.log({message: "Matching filters", matches: matched});
    }