管理篩選器

您可以使用篩選器為帳戶設定進階篩選規則。篩選器可根據傳入郵件的屬性或內容,自動新增或移除標籤,或將電子郵件轉寄至已驗證的別名

如要瞭解如何create列出取得刪除篩選器,請參閱「篩選器參考資料」。

符合條件

您可以依寄件者、主旨、日期、大小和訊息內容等屬性篩選訊息。任何使用 Gmail 進階搜尋語法的查詢,也可以用於篩選器。常見的篩選器模式包括:

篩選器 相符組合
criteria.from='sender@example.com' 來自 sender@example.com 的所有電子郵件
criteria.size=10485760
criteria.sizeComparison='larger'
所有大小超過 10 MB 的電子郵件
criteria.hasAttachment=true 所有含有附件的電子郵件
criteria.subject='[People with Pets]' 主旨中含有 [People with Pets] 字串的所有電子郵件
criteria.query='"my important project"' 所有包含 my important project 字串的電子郵件
criteria.negatedQuery='"secret knock"' 所有不含 secret knock 字串的電子郵件

如果篩選器設有多個條件,則郵件必須符合所有條件,系統才會套用篩選器。

動作

您可以將動作套用至符合篩選條件的郵件。郵件可能會轉寄至已驗證的電子郵件地址,或是新增或移除標籤

您可以新增或移除標籤,變更電子郵件的處理方式。舉例來說,常見的動作包括:

動作 效果
action.removeLabelIds=['INBOX'] 封存電子郵件 (略過收件匣)
action.removeLabelIds=['UNREAD'] 標示為已讀取
action.removeLabelIds=['SPAM'] 永不標示為垃圾內容
action.removeLabelIds=['IMPORTANT'] 永不標示為重要
action.addLabelIds=['IMPORTANT'] 標示為重要
action.addLabelIds=['TRASH'] 刪除電子郵件
action.addLabelIds=['STARRED'] 標示為已加星號
action.addLabelIds=['<user label id>'] 使用者定義的標籤。每個篩選條件只能使用一個使用者定義的標籤。

範例

以下是更完整的範例,說明如何為郵寄清單中的訊息加上標籤並封存。

Java

gmail/snippets/src/main/java/CreateFilter.java
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Filter;
import com.google.api.services.gmail.model.FilterAction;
import com.google.api.services.gmail.model.FilterCriteria;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;

/* Class to demonstrate the use of Gmail Create Filter API */
public class CreateFilter {
  /**
   * Create a new filter.
   *
   * @param labelId - ID of the user label to add
   * @return the created filter id, {@code null} otherwise.
   * @throws IOException - if service account credentials file not found.
   */
  public static String createNewFilter(String labelId) throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(GmailScopes.GMAIL_SETTINGS_BASIC,
            GmailScopes.GMAIL_LABELS);
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);

    // Create the gmail API client
    Gmail service = new Gmail.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Gmail samples")
        .build();

    try {
      // Filter the mail from sender and archive them(skip the inbox)
      Filter filter = new Filter()
          .setCriteria(new FilterCriteria()
              .setFrom("gduser2@workspacesamples.dev"))
          .setAction(new FilterAction()
              .setAddLabelIds(Arrays.asList(labelId))
              .setRemoveLabelIds(Arrays.asList("INBOX")));

      Filter result = service.users().settings().filters().create("me", filter).execute();
      // Prints the new created filter ID
      System.out.println("Created filter " + result.getId());
      return result.getId();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      GoogleJsonError error = e.getDetails();
      if (error.getCode() == 403) {
        System.err.println("Unable to create filter: " + e.getDetails());
      } else {
        throw e;
      }
    }
    return null;
  }
}

Python

gmail/snippet/settings snippets/create_filter.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def create_filter():
  """Create a filter.
  Returns: Draft object, including filter id.

  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()

  try:
    # create gmail api client
    service = build("gmail", "v1", credentials=creds)

    label_name = "IMPORTANT"
    filter_content = {
        "criteria": {"from": "gsuder1@workspacesamples.dev"},
        "action": {
            "addLabelIds": [label_name],
            "removeLabelIds": ["INBOX"],
        },
    }

    # pylint: disable=E1101
    result = (
        service.users()
        .settings()
        .filters()
        .create(userId="me", body=filter_content)
        .execute()
    )
    print(f'Created filter with id: {result.get("id")}')

  except HttpError as error:
    print(f"An error occurred: {error}")
    result = None

  return result.get("id")


if __name__ == "__main__":
  create_filter()