管理篩選器

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

如要瞭解如何建立清單get刪除 篩選器,請參閱篩選器參考資料

符合條件

您可以依寄件者、主旨日期、大小和訊息內容等屬性篩選訊息。任何使用 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/settingssnippet/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()