Managing Filters

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.

For information on how to create, list, get, or delete filters, see the Filters reference.

Matching criteria

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:

Filter Matches
criteria.from='' All emails from
All emails larger than 10MB
criteria.hasAttachment=true All emails with an attachment
criteria.subject='[People with Pets]' 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.


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.


The following is a more complete example showing how to label and archive messages from a mailing list.


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 for
            guides on implementing OAuth2 for your application. */
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);

    // Create the gmail API client
    Gmail service = new Gmail.Builder(new NetHttpTransport(),
        .setApplicationName("Gmail samples")

    try {
      // Filter the mail from sender and archive them(skip the inbox)
      Filter filter = new Filter()
          .setCriteria(new FilterCriteria()
          .setAction(new FilterAction()

      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;


gmail/snippet/settings snippets/
from __future__ import print_function

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
    for guides on implementing OAuth2 for the application.
    creds, _ = google.auth.default()

        # create gmail api client
        service = build('gmail', 'v1', credentials=creds)

        label_name = 'IMPORTANT'
        filter_content = {
            'criteria': {
                'from': ''
            '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__':