전달 관리

컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.

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

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

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

전달 주소를 만들거나, 나열, 가져오기, 삭제하는 방법은 전달주소 참조를 참조하세요.

전달 설정을 가져오거나 업데이트하는 방법에 대한 자세한 내용은 설정 참조를 확인하세요.

전달 주소 만들기 및 확인

사용하기 전에 전달 주소를 만들어야 합니다. 사용자가 주소 소유권도 확인해야 하는 경우가 있습니다.

Gmail에서 전달 주소에 대한 사용자 인증을 요구하는 경우 주소는 pending 상태로 반환됩니다. 확인 메시지가 대상 이메일 주소로 자동 전송됩니다. 이메일 주소 소유자가 확인 절차를 완료해야 사용할 수 있습니다.

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

자동 전달 사용 설정

updateAutoForward 메서드를 호출하여 계정에 자동 전달을 사용 설정합니다. 호출 시 등록 및 확인된 전달 주소와 전달한 메시지에 취할 작업이 모두 필요합니다.

예를 들어 자동 전달을 사용 설정하고 전달된 메일을 휴지통으로 이동하려면 다음 안내를 따르세요.

자바

gmail/snippets/src/main/java/EnableForward.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/settingssnippet/enable_forward.py
from __future__ import print_function

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

자동 전달을 사용 중지하려면 updateAutoForward를 호출하고 enabled 속성을 false로 설정합니다.

특정 메일 전달

자동 전달은 수신된 모든 메시지를 대상 계정으로 전송합니다. 선택적으로 메시지를 전달하려면 필터를 사용하여 메시지 속성 또는 콘텐츠에 대한 응답으로 전달하는 규칙을 만듭니다.