Gmail 필터 관리

이 문서에서는 Gmail API에서 필터를 사용하는 방법을 설명합니다.

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

Gmail 필터를 만들기, 나열하기, 가져오기 또는 삭제하기하는 방법에 관한 자세한 내용은 settings.filters 리소스를 참고하세요.

일치 기준

발신자, 제목, 날짜, 크기, 메시지 내용과 같은 속성으로 메일을 필터링합니다. 필터는 전체 이메일 대화목록이 아닌 특정 메일에만 적용됩니다. 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을 적용합니다. Action를 사용하면 인증된 이메일 주소로 메시지를 전달하거나 라벨을 추가 및 삭제할 수 있습니다.

라벨을 추가하거나 삭제하여 이메일의 처리 상태를 변경합니다. 예를 들어 일반적인 작업은 다음과 같습니다.

작업 효과
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>'] 사용자 정의 라벨로 메일에 태그를 지정합니다. 필터당 사용자 정의 라벨은 하나만 허용됩니다.

코드 샘플

다음 코드 샘플은 메일링 리스트의 메시지에 라벨을 지정하고 보관하는 방법을 보여줍니다.

자바

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