Searching Gmail Messages by Gmail Filters using Google Apps Script

Gists

This is a sample script for searching Gmail messages by Gmail Filters using Google Apps Script.

At Gmail, users can set the filter for the Emails. With this filter, users can filter the Emails of Gmail. But, when the users want to search by the installed filter using Google Apps Script, unfortunately, it seems that this cannot be directly achieved. For example, messages cannot be searched using a filter ID.

In this sample script, the messages are searched by the filter ID.

Before you use this script, please enable Gmail API at Advanced Google services.

Sample script

You can retrieve the filter IDs using the following script. You can see the filter IDs and the criteria.

const filters = Gmail.Users.Settings.Filters.list("me");
console.log(filters);

The following sample script searches messages with the filter ID.

function myFunction() {
  const id = "###"; // Please set filter ID.

  const filters = Gmail.Users.Settings.Filters.list("me");
  const obj = filters.filter.reduce(
    (
      o,
      {
        id,
        criteria: {
          from,
          to,
          subject,
          query,
          negatedQuery,
          hasAttachment,
          size,
          sizeComparison,
        },
      }
    ) => (
      (o[id] = [
        from ? `from:(${from})` : "",
        to ? `to:(${to})` : "",
        subject ? `subject:(${subject})` : "",
        query || "",
        negatedQuery ? `-{${negatedQuery}}` : "",
        hasAttachment ? "has:attachment" : "",
        size && sizeComparison ? `${sizeComparison}:${size}` : "",
      ]
        .join(" ")
        .trim()),
      o
    ),
    {}
  );
  if (obj[id]) {
    GmailApp.search(obj[id], 0, 5).forEach((t) => {
      t.getMessages().forEach((m) => {
        console.log({
          from: m.getFrom(),
          to: m.getTo(),
          subject: m.getSubject(),
          date: m.getDate(),
        });
      });
    });
  } else {
    throw new Error("Inputted ID was not found.");
  }
}
  • In this sample, 5 messages are searched. If you want to retrieve more searched messages, please modify GmailApp.search(obj[id], 0, 5) to GmailApp.search(obj[id]). This method retrieves 500 messages as the maximum result. So, when you want to retrieve all messages, please use search(query, start, max). Ref

Reference

 Share!