이메일 전달 관리

이 문서에서는 Gmail API에서 이메일 전달을 구성하는 방법을 설명합니다.

settings 리소스를 사용하여 계정의 전달을 구성할 수 있습니다. 이메일 주소를 전달 이메일 주소로 사용하려면 다음 기준 중 하나를 충족해야 합니다.

  • 이메일 주소가 인증되었습니다. 자세한 내용은 전달 주소 만들기 및 확인하기를 참고하세요.
  • 이메일 주소가 발신자와 동일한 도메인에 속합니다.
  • 이메일 주소가 발신자와 동일한 도메인 내의 하위 도메인에 속합니다.
  • 이메일 주소가 동일한 Google Workspace 계정의 일부로 구성된 도메인 별칭에 속합니다.

전달 이메일 주소가 이러한 규칙 중 하나를 준수하지 않으면 API를 사용한 전달 설정이 실패합니다.

전달 주소를 만들기, 나열, 가져오기 또는 삭제하는 방법에 관한 자세한 내용은 settings.forwardingAddresses 리소스의 메서드를 참고하세요.

자동 전달 설정을 가져오기하거나 업데이트하는 방법에 관한 자세한 내용은 settings 리소스의 메서드를 참고하세요.

전달 주소 만들기 및 확인하기

전달 주소를 사용하려면 먼저 만들어야 합니다. 경우에 따라 사용자는 주소의 소유권도 확인해야 합니다.

Gmail에서 전달 주소에 대한 사용자 인증을 요구하는 경우 주소는 pendingVerificationStatus와 함께 반환됩니다. 인증 메일이 타겟 이메일 주소로 자동 전송됩니다. 이메일 주소를 사용하려면 이메일 주소의 소유자가 인증 절차를 완료해야 합니다.

확인이 필요하지 않은 전달 주소의 확인 상태는 accepted입니다.

자동 전달 사용 설정

다른 이메일 주소로 새 메일을 모두 전달하도록 선택할 수 있습니다.

이렇게 하려면 updateAutoForwarding 메서드를 호출하여 계정의 자동 전달을 사용 설정합니다. 이 호출에는 등록되고 인증된 전달 주소와 전달된 메일에 취할 조치가 필요합니다. 이러한 값은 AutoForwarding 객체를 사용하여 설정됩니다.

disposition 필드는 메시지가 전달된 후 메시지 상태를 설정하는 데 사용됩니다. 기본값은 dispositionUnspecified이지만 이 필드를 dispositionUnspecified로 설정할 수는 없습니다.

다음 코드 샘플은 자동 전달을 사용 설정한 후 전달된 메시지를 휴지통으로 이동하는 방법을 보여줍니다.

자바

gmail/snippets/src/main/java/EnableForwarding.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.AutoForwarding;
import com.google.api.services.gmail.model.ForwardingAddress;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;

/* Class to demonstrate the use of Gmail Enable Forwarding API */
public class EnableForwarding {
  /**
   * Enable the auto-forwarding for an account.
   *
   * @param forwardingEmail - Email address of the recipient whose email will be forwarded.
   * @return forwarding id and metadata, {@code null} otherwise.
   * @throws IOException - if service account credentials file not found.
   */
  public static AutoForwarding enableAutoForwarding(String forwardingEmail) 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_SHARING);
    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 {
      // Enable auto-forwarding and move forwarded messages to the trash
      ForwardingAddress address = new ForwardingAddress()
          .setForwardingEmail(forwardingEmail);
      ForwardingAddress createAddressResult = service.users().settings().forwardingAddresses()
          .create("me", address).execute();
      if (createAddressResult.getVerificationStatus().equals("accepted")) {
        AutoForwarding autoForwarding = new AutoForwarding()
            .setEnabled(true)
            .setEmailAddress(address.getForwardingEmail())
            .setDisposition("trash");
        autoForwarding =
            service.users().settings().updateAutoForwarding("me", autoForwarding).execute();
        System.out.println(autoForwarding.toPrettyString());
        return autoForwarding;
      }
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      GoogleJsonError error = e.getDetails();
      if (error.getCode() == 403) {
        System.err.println("Unable to enable forwarding: " + e.getDetails());
      } else {
        throw e;
      }
    }
    return null;
  }
}

Python

gmail/snippet/settings snippets/enable_forwarding.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def enable_forwarding():
  """Enable email forwarding.
  Returns:Draft object, including forwarding id and result meta data.

  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)

    address = {"forwardingEmail": "gduser1@workspacesamples.dev"}

    # pylint: disable=E1101
    result = (
        service.users()
        .settings()
        .forwardingAddresses()
        .create(userId="me", body=address)
        .execute()
    )
    if result.get("verificationStatus") == "accepted":
      body = {
          "emailAddress": result.get("forwardingEmail"),
          "enabled": True,
          "disposition": "trash",
      }
      # pylint: disable=E1101
      result = (
          service.users()
          .settings()
          .updateAutoForwarding(userId="me", body=body)
          .execute()
      )
      print(f"Forwarding is enabled : {result}")

  except HttpError as error:
    print(f"An error occurred: {error}")
    result = None

  return result


if __name__ == "__main__":
  enable_forwarding()

자동 전달을 사용 중지하려면 updateAutoForwarding 메서드를 호출하고 AutoForwarding 객체의 enabled 필드를 false로 설정합니다.

특정 메시지 전달

자동 전달은 수신된 모든 Gmail 메일을 대상 계정으로 전송합니다. 특정 메일을 전달하려면 메일 속성 또는 콘텐츠에 따라 메일을 전달하는 규칙을 만드는 필터를 설정하세요.

여러 계정으로 메일을 전달하려면 전달 이메일 주소마다 필터를 만드세요.