管理电子邮件转发

本文档介绍了如何在 Gmail API 中配置电子邮件转发。

您可以使用 settings 资源为账号配置转发。电子邮件地址必须满足以下条件之一,才能用作转发电子邮件地址:

  • 电子邮件地址已通过验证。如需了解详情,请参阅创建和验证转发地址
  • 电子邮件地址与发件人属于同一网域。
  • 电子邮件地址属于发件人所在网域内的子网域。
  • 相应电子邮件地址属于配置为同一 Google Workspace 账号一部分的网域别名。

如果转发电子邮件地址不符合上述任一规则,则使用 API 设置转发会失败。

如需了解如何创建列出获取删除转发地址,请参阅 settings.forwardingAddresses 资源的方法。

如需了解如何获取更新自动转发设置,请参阅 settings 资源中的方法。

创建和验证转发地址

您必须先创建转发地址,然后才能使用它们。在某些情况下,用户还必须验证地址的所有权。

如果 Gmail 要求对转发地址进行用户验证,则返回的地址的 VerificationStatuspending。系统会自动向目标电子邮件地址发送一封验证邮件。电子邮件地址的所有者必须先完成验证流程,然后才能使用该地址。

无需验证的转寄地址的验证状态为 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 邮件发送到目标账号。如需转发特定邮件,请设置过滤器,以创建规则,根据邮件属性或内容转发邮件。

如需将邮件转发到多个账号,请为每个转发电子邮件地址创建一个过滤器。