필터 관리

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

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

일치 기준

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

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

자바

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