管理过滤器

您可以使用过滤条件为账号配置高级过滤规则。过滤器可以根据传入邮件的属性或内容,自动添加或移除标签,或将电子邮件转发到经过验证的别名

如需了解如何create列出获取删除过滤条件,请参阅过滤条件参考文档

匹配条件

您可以按发件人、主题、日期、大小和邮件内容等属性过滤邮件。您还可以在过滤器中使用任何使用 Gmail 高级搜索语法的查询。例如,常见的过滤器模式包括:

过滤 配对
criteria.from='sender@example.com' 来自 sender@example.com 的所有电子邮件
criteria.size=10485760
criteria.sizeComparison='larger'
所有大于 10MB 的电子邮件
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()