管理过滤器
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
您可以使用过滤条件为账号配置高级过滤规则。过滤器可以根据收到的邮件的属性或内容,自动添加或移除标签,或者将电子邮件转发到已验证的别名。
如需了解如何创建、列出、获取或删除过滤条件,请参阅过滤条件参考文档。
匹配条件
您可以按发件人、主题日期、大小和邮件内容等属性过滤邮件。任何使用 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>'] |
使用用户定义的标签标记邮件。每个过滤条件只能包含一个用户定义的标签。 |
示例
以下是一个更完整的示例,展示了如何为邮件列表中的邮件添加标签并将其归档。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-27。
[null,null,["最后更新时间 (UTC):2025-08-27。"],[],[],null,["# Managing Filters\n\nYou can use [Filters](/workspace/gmail/api/v1/reference/users/settings/filters) to\nconfigure advanced filtering rules for an account. Filters can automatically\nadd or remove [labels](/workspace/gmail/api/guides/labels) or forward emails to\n[verified aliases](/workspace/gmail/api/guides/forwarding_settings) based on the\nattributes or content of the incoming message.\n\nFor information on how to\n[create](/workspace/gmail/api/v1/reference/users/settings/filters/create),\n[list](/workspace/gmail/api/v1/reference/users/settings/filters/list),\n[get](/workspace/gmail/api/v1/reference/users/settings/filters/get),\nor [delete](/workspace/gmail/api/v1/reference/users/settings/filters/delete) filters,\nsee the [Filters reference](/workspace/gmail/api/v1/reference/users/settings/filters).\n\nMatching criteria\n-----------------\n\nYou can filter messages by properties such as the sender, subject date, size,\nand message contents. Any query using Gmail's\n[advanced search syntax](https://support.google.com/mail/answer/7190)\ncan also be used in a filter. For example, common filter patterns include:\n\n| Filter | Matches |\n|-------------------------------------------------------------|----------------------------------------------------------------|\n| `criteria.from='sender@example.com'` | All emails from `sender@example.com` |\n| `criteria.size=10485760` `criteria.sizeComparison='larger'` | All emails larger than 10MB |\n| `criteria.hasAttachment=true` | All emails with an attachment |\n| `criteria.subject='[People with Pets]'` | All emails with the string `[People with Pets]` in the subject |\n| `criteria.query='\"my important project\"'` | All emails containing the string `my important project` |\n| `criteria.negatedQuery='\"secret knock\"'` | All emails that do not contain the string `secret knock` |\n\nIf multiple criteria are present in a filter, a message must satisfy all\ncriteria for the filter to apply.\n\nActions\n-------\n\nYou can apply an [action](/workspace/gmail/api/v1/reference/users/settings/filters#resource-representations)\nto messages matching the filter criteria. Messages may be forwarded to a\nverified email address, or have [labels](/workspace/gmail/api/guides/labels) added or removed.\n\nYou can add or remove labels to change the disposition of the email. For example,\nsome common actions include:\n\n| Action | Effect |\n|------------------------------------------|--------------------------------------------------------------------------------------------|\n| `action.removeLabelIds=['INBOX']` | Archive the email (skip the inbox) |\n| `action.removeLabelIds=['UNREAD']` | Mark as read |\n| `action.removeLabelIds=['SPAM']` | Never mark as spam |\n| `action.removeLabelIds=['IMPORTANT']` | Never mark as important |\n| `action.addLabelIds=['IMPORTANT']` | Mark as important |\n| `action.addLabelIds=['TRASH']` | Delete the email |\n| `action.addLabelIds=['STARRED']` | Mark as starred |\n| `action.addLabelIds=['\u003cuser label id\u003e']` | Tag the mail with a user-defined label. Only one user-defined label is allowed per filter. |\n\nExamples\n--------\n\nThe following is a more complete example showing how to label and archive\nmessages from a mailing list. \n\n### Java\n\ngmail/snippets/src/main/java/CreateFilter.java \n[View on GitHub](https://github.com/googleworkspace/java-samples/blob/main/gmail/snippets/src/main/java/CreateFilter.java) \n\n```java\nimport com.google.api.client.googleapis.json.GoogleJsonError;\nimport com.google.api.client.googleapis.json.GoogleJsonResponseException;\nimport com.google.api.client.http.HttpRequestInitializer;\nimport com.google.api.client.http.javanet.NetHttpTransport;\nimport com.google.api.client.json.gson.GsonFactory;\nimport com.google.api.services.gmail.Gmail;\nimport com.google.api.services.gmail.GmailScopes;\nimport com.google.api.services.gmail.model.Filter;\nimport com.google.api.services.gmail.model.FilterAction;\nimport com.google.api.services.gmail.model.FilterCriteria;\nimport com.google.auth.http.HttpCredentialsAdapter;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport java.io.IOException;\nimport java.util.Arrays;\n\n/* Class to demonstrate the use of Gmail Create Filter API */\npublic class CreateFilter {\n /**\n * Create a new filter.\n *\n * @param labelId - ID of the user label to add\n * @return the created filter id, {@code null} otherwise.\n * @throws IOException - if service account credentials file not found.\n */\n public static String createNewFilter(String labelId) throws IOException {\n /* Load pre-authorized user credentials from the environment.\n TODO(developer) - See https://developers.google.com/identity for\n guides on implementing OAuth2 for your application. */\n GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()\n .createScoped(GmailScopes.GMAIL_SETTINGS_BASIC,\n GmailScopes.GMAIL_LABELS);\n HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);\n\n // Create the gmail API client\n Gmail service = new Gmail.Builder(new NetHttpTransport(),\n GsonFactory.getDefaultInstance(),\n requestInitializer)\n .setApplicationName(\"Gmail samples\")\n .build();\n\n try {\n // Filter the mail from sender and archive them(skip the inbox)\n Filter filter = new Filter()\n .setCriteria(new FilterCriteria()\n .setFrom(\"gduser2@workspacesamples.dev\"))\n .setAction(new FilterAction()\n .setAddLabelIds(Arrays.asList(labelId))\n .setRemoveLabelIds(Arrays.asList(\"INBOX\")));\n\n Filter result = service.users().settings().filters().create(\"me\", filter).execute();\n // Prints the new created filter ID\n System.out.println(\"Created filter \" + result.getId());\n return result.getId();\n } catch (GoogleJsonResponseException e) {\n // TODO(developer) - handle error appropriately\n GoogleJsonError error = e.getDetails();\n if (error.getCode() == 403) {\n System.err.println(\"Unable to create filter: \" + e.getDetails());\n } else {\n throw e;\n }\n }\n return null;\n }\n}\n```\n\n### Python\n\ngmail/snippet/settings snippets/create_filter.py \n[View on GitHub](https://github.com/googleworkspace/python-samples/blob/main/gmail/snippet/settings snippets/create_filter.py) \n\n```python\nimport google.auth\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\n\ndef create_filter():\n \"\"\"Create a filter.\n Returns: Draft object, including filter id.\n\n Load pre-authorized user credentials from the environment.\n TODO(developer) - See https://developers.google.com/identity\n for guides on implementing OAuth2 for the application.\n \"\"\"\n creds, _ = google.auth.default()\n\n try:\n # create gmail api client\n service = build(\"gmail\", \"v1\", credentials=creds)\n\n label_name = \"IMPORTANT\"\n filter_content = {\n \"criteria\": {\"from\": \"gsuder1@workspacesamples.dev\"},\n \"action\": {\n \"addLabelIds\": [label_name],\n \"removeLabelIds\": [\"INBOX\"],\n },\n }\n\n # pylint: disable=E1101\n result = (\n service.users()\n .settings()\n .filters()\n .create(userId=\"me\", body=filter_content)\n .execute()\n )\n print(f'Created filter with id: {result.get(\"id\")}')\n\n except HttpError as error:\n print(f\"An error occurred: {error}\")\n result = None\n\n return result.get(\"id\")\n\n\nif __name__ == \"__main__\":\n create_filter()\n```"]]