管理電子郵件轉寄

本文說明如何在 Gmail API 中設定電子郵件轉寄。

您可以使用 settings 資源設定帳戶的轉送功能。如要使用電子郵件地址轉寄郵件,該地址必須符合下列其中一項條件:

  • 電子郵件地址已通過驗證。詳情請參閱「建立及驗證轉寄地址」。
  • 電子郵件地址與寄件者位於相同網域。
  • 電子郵件地址屬於與寄件者相同網域的子網域。
  • 電子郵件地址屬於網域別名,該別名已設定為相同 Google Workspace 帳戶的一部分。

如果轉寄電子郵件地址不符合其中一項規則,透過 API 設定轉寄功能就會失敗。

如要瞭解如何建立列出取得刪除轉寄地址,請參閱 settings.forwardingAddresses 資源的方法。

如要瞭解如何取得更新自動轉寄設定,請參閱 settings 資源的方法。

建立及驗證轉寄地址

您必須先建立轉寄地址,才能使用這些地址。在某些情況下,使用者也必須驗證地址擁有權。

如果 Gmail 要求驗證轉寄地址,API 會傳回該地址,並在 VerificationStatus 中加入 pending。Gmail 會自動將驗證訊息傳送到目標電子郵件地址。電子郵件地址擁有者必須完成驗證程序,你才能使用該地址。

不需要驗證的轉寄地址驗證狀態為 accepted

啟用自動轉寄功能

你可以選擇將所有新郵件都轉寄到其他電子郵件地址。

如要啟用帳戶的自動轉寄功能,請呼叫 updateAutoForwarding 方法。這項呼叫需要已註冊並通過驗證的轉寄地址,以及對轉寄郵件採取的動作。在 AutoForwarding 物件中設定這些值。

使用 disposition 欄位設定轉寄郵件後的郵件狀態。雖然預設值為 dispositionUnspecified,但您無法將這個欄位設為 dispositionUnspecified

下列程式碼範例說明如何啟用自動轉寄功能,然後將轉寄的郵件移至垃圾桶:

Java

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 郵件轉寄到目標帳戶。如要轉寄特定郵件,請設定篩選器,根據郵件屬性或內容建立轉寄規則。

如要將郵件轉寄到多個帳戶,請為每個轉寄電子郵件地址建立篩選器。