管理过滤器

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

如需了解如何创建列出获取删除过滤器,请参阅过滤器参考

匹配条件

您可以按发件人、主题日期、大小和消息内容等属性过滤消息。使用 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

您可以对符合过滤条件的消息应用操作。邮件可能会转发到经过验证的电子邮件地址,或者添加或移除标签

您可以添加或移除标签,以更改电子邮件的处理方式。例如,一些常见操作包括:

操作 效果
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 fragment/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()