管理轉寄功能

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

您可以使用「Settings」(設定) 來設定帳戶的轉寄功能。這個地址必須滿足下列其中一項條件,才能做為轉寄電子郵件地址:

  • 電子郵件地址已通過驗證。詳情請參閱建立及驗證轉寄地址一文。
  • 該電子郵件地址與寄件者隸屬於同一網域。
  • 該電子郵件地址隸屬於某個寄件者所屬網域中的子網域。
  • 該電子郵件地址屬於同一個 Google Workspace 帳戶設定的網域別名。

如果轉寄電子郵件地址不符合其中一項規則,則使用 API 進行轉寄會失敗。

如要瞭解如何建立列出取得刪除轉寄地址,請參閱 ForwardAddress 參考資料

如要瞭解如何取得 getupdate 轉送設定,請參閱設定參考資料

建立及驗證轉寄地址

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

如果 Gmail 要求使用者驗證轉寄地址,系統就會傳回地址為 pending 的狀態。系統會自動傳送一封驗證郵件到 目標電子郵件地址,電子郵件地址擁有者必須完成驗證程序才能使用。

不需要驗證的轉寄地址會顯示 accepted 的驗證狀態。

啟用自動轉寄功能

呼叫 updateAutoForward 方法以啟用帳戶的自動轉寄功能。這個呼叫需要已註冊且經驗證的轉寄地址,以及需要對轉寄的郵件採取動作。

舉例來說,如要啟用自動轉寄功能,並將轉寄的郵件移到垃圾桶:

Java

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/settings snippets/enable_forwarding.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

轉寄特定郵件

自動轉寄功能會將所有收到的郵件傳送至目標帳戶,如要選擇性轉寄訊息,請使用篩選器建立規則,以轉寄訊息屬性或內容。