การจัดการตัวกรอง

คุณสามารถใช้ตัวกรองเพื่อกำหนดค่ากฎการกรองขั้นสูงสำหรับบัญชีได้ ตัวกรองสามารถ เพิ่มหรือนำป้ายกำกับออกโดยอัตโนมัติ หรือส่งต่ออีเมลไปยัง ชื่อแทนที่ยืนยันแล้ว ตามแอตทริบิวต์หรือเนื้อหาของข้อความขาเข้า

ดูข้อมูลเกี่ยวกับวิธีสร้าง รายการ รับ หรือลบตัวกรองได้ที่ข้อมูลอ้างอิงตัวกรอง

เกณฑ์การจับคู่

คุณสามารถกรองข้อความตามพร็อพเพอร์ตี้ เช่น ผู้ส่ง วันที่ของเรื่อง ขนาด และเนื้อหาข้อความ คำค้นหาที่ใช้ไวยากรณ์การค้นหาขั้นสูงของ 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>'] ติดแท็กอีเมลด้วยป้ายกำกับที่ผู้ใช้กำหนด ใช้ตัวกรองที่กำหนดโดยผู้ใช้ได้เพียง 1 รายการต่อตัวกรอง

ตัวอย่าง

ต่อไปนี้เป็นตัวอย่างที่สมบูรณ์ยิ่งขึ้นซึ่งแสดงวิธีติดป้ายกำกับและจัดเก็บข้อความจากรายชื่ออีเมล

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 ข้อมูลโค้ด/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()