Zarządzanie filtrami Gmaila

Z tego dokumentu dowiesz się, jak korzystać z filtrów w Gmail API.

Aby skonfigurować zaawansowane reguły filtrowania na koncie, możesz użyć zasobu settings.filters. Filtry mogą automatycznie dodawać lub usuwać etykiety albo przekazywać e-maile na zweryfikowane aliasy na podstawie atrybutów lub treści wiadomości przychodzącej.

Informacje o tym, jak tworzyć, wyświetlać, pobierać i usuwać filtry Gmaila, znajdziesz w tym settings.filters artykule.

Kryteria dopasowania

Filtruj wiadomości według właściwości, takich jak nadawca, temat, data, rozmiar i treść wiadomości. Filtry są stosowane tylko do konkretnych wiadomości, a nie do całego wątku e-maila. W filtrze można też użyć dowolnego zapytania z zaawansowaną składnią wyszukiwania Gmaila. Typowe wzorce filtrów to na przykład:

Filtruj Dopasowania
criteria.from='sender@example.com' E-maile od sender@example.com
criteria.size=10485760
criteria.sizeComparison='larger'
e-maile większe niż 10 MB;
criteria.hasAttachment=true E-maile z załącznikiem
criteria.subject='[People with Pets]' E-maile z [People with Pets] w temacie
criteria.query='"my important project"' E-maile zawierające my important project
criteria.negatedQuery='"secret knock"' E-maile niezawierające secret knock

Jeśli filtr zawiera wiele kryteriów, aby go zastosować, wiadomość musi spełniać wszystkie kryteria.

Działania

Zastosuj Action do wiadomości pasujących do kryteriów filtra. Dzięki Action możesz przekazywać wiadomości na zweryfikowany adres e-mail oraz dodawać i usuwać etykiety.

Dodaj lub usuń etykiety, aby zmienić stan e-maila. Na przykład do typowych działań należą:

Działanie Efekt
action.removeLabelIds=['INBOX'] Archiwizowanie e-maila (pomijanie folderu Odebrane)
action.removeLabelIds=['UNREAD'] Oznacz jako przeczytane
action.removeLabelIds=['SPAM'] Nigdy nie oznaczaj jako spam
action.removeLabelIds=['IMPORTANT'] Nigdy nie oznaczaj jako ważne
action.addLabelIds=['IMPORTANT'] Oznacz jako ważne
action.addLabelIds=['TRASH'] Usuń e-mail
action.addLabelIds=['STARRED'] Oznaczanie jako ulubione
action.addLabelIds=['<user label id>'] oznaczyć pocztę etykietą zdefiniowaną przez użytkownika; W przypadku każdego filtra można użyć tylko 1 etykiety zdefiniowanej przez użytkownika.

Przykładowe fragmenty kodu

Poniższe przykłady kodu pokazują, jak oznaczać i archiwizować wiadomości z listy mailingowej:

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()