フィルタの管理

フィルタを使用すると、アカウントの高度なフィルタリング ルールを構成できます。フィルタを使用すると、受信メッセージの属性や内容に基づいて、ラベルを自動的に追加または削除したり、確認済みのエイリアスにメールを転送したりできます。

フィルタを作成一覧表示取得削除する方法については、フィルタのリファレンスをご覧ください。

一致条件

送信者、件名の日付、サイズ、メッセージの内容などのプロパティでメッセージをフィルタできます。フィルタでは、Gmail の検索オプション構文を使用したクエリも使用できます。たとえば、次のような一般的なフィルタ パターンがあります。

フィルタ 一致
criteria.from='sender@example.com' sender@example.com からのすべてのメール
criteria.size=10485760
criteria.sizeComparison='larger'
10 MB を超えるすべてのメール
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>'] ユーザー定義のラベルでメールにタグを付けます。フィルタごとに使用できるユーザー定義のラベルは 1 つのみです。

以下に、メーリング リストからのメールにラベルを付けてアーカイブする方法の詳細な例を示します。

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