필터 관리

필터를 사용하여 계정에 고급 필터링 규칙을 구성할 수 있습니다. 필터는 자동으로 라벨을 추가 또는 삭제하거나 수신 메시지의 속성 또는 콘텐츠에 따라 확인된 별칭으로 이메일을 전달할 수 있습니다.

필터를 만들기, 나열, 가져오기, 삭제하는 방법에 대한 자세한 내용은 필터 참조를 확인하세요.

일치 기준

발신자, 제목 날짜, 크기, 메시지 내용과 같은 속성별로 메시지를 필터링할 수 있습니다. 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>'] 사용자 정의 라벨을 사용하여 메일에 태그를 지정합니다. 필터당 사용자 정의 라벨은 하나만 허용됩니다.

다음은 메일링 리스트의 메시지에 라벨을 지정하고 보관처리하는 방법을 보여주는 보다 완전한 예입니다.

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/스니펫/설정 스니펫/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()