Quản lý bộ lọc

Bạn có thể sử dụng Bộ lọc để định cấu hình các quy tắc lọc nâng cao cho một tài khoản. Các bộ lọc có thể tự động thêm hoặc xoá nhãn hoặc chuyển tiếp email tới email đại diện đã xác minh dựa trên các thuộc tính hoặc nội dung của thư đến.

Để biết thông tin về cách tạo, danh sách, nhận hoặc xoá bộ lọc, hãy xem Tài liệu tham khảo về bộ lọc.

Tiêu chí khớp

Bạn có thể lọc thư theo các thuộc tính như người gửi, ngày chủ đề, kích thước và nội dung thư. Bất kỳ truy vấn nào sử dụng cú pháp tìm kiếm nâng cao của Gmail cũng có thể được dùng trong bộ lọc. Ví dụ: các mẫu bộ lọc phổ biến bao gồm:

Lọc Khớp với
criteria.from='sender@example.com' Tất cả email từ sender@example.com
criteria.size=10485760
criteria.sizeComparison='larger'
Tất cả email lớn hơn 10 MB
criteria.hasAttachment=true Tất cả email có tệp đính kèm
criteria.subject='[People with Pets]' Tất cả email có chuỗi [People with Pets] trong tiêu đề
criteria.query='"my important project"' Tất cả email chứa chuỗi my important project
criteria.negatedQuery='"secret knock"' Tất cả email không chứa chuỗi secret knock

Nếu có nhiều tiêu chí trong một bộ lọc, thì một thông báo phải đáp ứng tất cả các tiêu chí để bộ lọc đó được áp dụng.

Thao tác

Bạn có thể áp dụng một hành động cho các tin nhắn khớp với tiêu chí lọc. Thư có thể được chuyển tiếp đến một địa chỉ email đã xác minh hoặc đã thêm hoặc xóa nhãn.

Bạn có thể thêm hoặc xoá nhãn để thay đổi bố cục của email. Ví dụ: một số thao tác phổ biến bao gồm:

Hành động Hiệu quả
action.removeLabelIds=['INBOX'] Lưu trữ email (bỏ qua hộp thư đến)
action.removeLabelIds=['UNREAD'] Đánh dấu là đã đọc
action.removeLabelIds=['SPAM'] Không bao giờ đánh dấu là thư rác
action.removeLabelIds=['IMPORTANT'] Không bao giờ đánh dấu là quan trọng
action.addLabelIds=['IMPORTANT'] Đánh dấu là quan trọng
action.addLabelIds=['TRASH'] Xoá email
action.addLabelIds=['STARRED'] Đánh dấu là có gắn dấu sao
action.addLabelIds=['<user label id>'] Gắn thẻ cho thư bằng nhãn do người dùng xác định. Chỉ cho phép một nhãn do người dùng xác định cho mỗi bộ lọc.

Ví dụ

Sau đây là ví dụ hoàn chỉnh hơn cho thấy cách gắn nhãn và lưu trữ thư từ danh sách gửi thư.

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 snippet/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()