Stay organized with collections
Save and categorize content based on your preferences.
You can use Filters to
configure advanced filtering rules for an account. Filters can automatically
add or remove labels or forward emails to
verified aliases based on the
attributes or content of the incoming message.
You can filter messages by properties such as the sender, subject date, size,
and message contents. Any query using Gmail's
advanced search syntax
can also be used in a filter. For example, common filter patterns include:
All emails with the string [People with Pets] in the subject
criteria.query='"my important project"'
All emails containing the string my important project
criteria.negatedQuery='"secret knock"'
All emails that do not contain the string secret knock
If multiple criteria are present in a filter, a message must satisfy all
criteria for the filter to apply.
Actions
You can apply an action
to messages matching the filter criteria. Messages may be forwarded to a
verified email address, or have labels added or removed.
You can add or remove labels to change the disposition of the email. For example,
some common actions include:
Action
Effect
action.removeLabelIds=['INBOX']
Archive the email (skip the inbox)
action.removeLabelIds=['UNREAD']
Mark as read
action.removeLabelIds=['SPAM']
Never mark as spam
action.removeLabelIds=['IMPORTANT']
Never mark as important
action.addLabelIds=['IMPORTANT']
Mark as important
action.addLabelIds=['TRASH']
Delete the email
action.addLabelIds=['STARRED']
Mark as starred
action.addLabelIds=['<user label id>']
Tag the mail with a user-defined label. Only one user-defined label is allowed per filter.
Examples
The following is a more complete example showing how to label and archive
messages from a mailing list.
importcom.google.api.client.googleapis.json.GoogleJsonError;importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.gmail.Gmail;importcom.google.api.services.gmail.GmailScopes;importcom.google.api.services.gmail.model.Filter;importcom.google.api.services.gmail.model.FilterAction;importcom.google.api.services.gmail.model.FilterCriteria;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.Arrays;/* Class to demonstrate the use of Gmail Create Filter API */publicclassCreateFilter{/** * 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. */publicstaticStringcreateNewFilter(StringlabelId)throwsIOException{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(GmailScopes.GMAIL_SETTINGS_BASIC,GmailScopes.GMAIL_LABELS);HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Create the gmail API clientGmailservice=newGmail.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Gmail samples").build();try{// Filter the mail from sender and archive them(skip the inbox)Filterfilter=newFilter().setCriteria(newFilterCriteria().setFrom("gduser2@workspacesamples.dev")).setAction(newFilterAction().setAddLabelIds(Arrays.asList(labelId)).setRemoveLabelIds(Arrays.asList("INBOX")));Filterresult=service.users().settings().filters().create("me",filter).execute();// Prints the new created filter IDSystem.out.println("Created filter "+result.getId());returnresult.getId();}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelyGoogleJsonErrorerror=e.getDetails();if(error.getCode()==403){System.err.println("Unable to create filter: "+e.getDetails());}else{throwe;}}returnnull;}}
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordefcreate_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 clientservice=build("gmail","v1",credentials=creds)label_name="IMPORTANT"filter_content={"criteria":{"from":"gsuder1@workspacesamples.dev"},"action":{"addLabelIds":[label_name],"removeLabelIds":["INBOX"],},}# pylint: disable=E1101result=(service.users().settings().filters().create(userId="me",body=filter_content).execute())print(f'Created filter with id: {result.get("id")}')exceptHttpErroraserror:print(f"An error occurred: {error}")result=Nonereturnresult.get("id")if__name__=="__main__":create_filter()
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-28 UTC."],[],[],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```"]]