Quản lý Chuyển tiếp

Bạn có thể sử dụng Cài đặt để định cấu hình tính năng chuyển tiếp cho một tài khoản. Để được dùng làm địa chỉ email chuyển tiếp, địa chỉ phải đáp ứng một trong các tiêu chí sau:

  • Địa chỉ email đã được xác minh. Để biết thêm thông tin, hãy xem phần Tạo và xác minh địa chỉ chuyển tiếp
  • Địa chỉ email thuộc cùng một miền với người gửi.
  • Địa chỉ email thuộc về một miền con trong cùng một miền của người gửi.
  • Địa chỉ email này thuộc về một bí danh miền, được định cấu hình trong cùng một tài khoản Google Workspace.

Nếu địa chỉ email chuyển tiếp không tuân thủ một trong các quy tắc này, thì việc thiết lập tính năng chuyển tiếp bằng API sẽ không thành công.

Để biết thông tin về cách tạo, danh sách, nhận hoặc xoá địa chỉ chuyển tiếp, hãy xem tài liệu tham khảo về RedirectAddresses.

Để biết thông tin về cách nhận hoặc cập nhật chế độ cài đặt chuyển tiếp, hãy xem Tài liệu tham khảo về chế độ cài đặt

Tạo và xác minh địa chỉ chuyển tiếp

Bạn phải tạo địa chỉ chuyển tiếp trước khi sử dụng. Trong một số trường hợp, người dùng cũng phải xác minh quyền sở hữu đối với địa chỉ đó.

Nếu Gmail yêu cầu người dùng xác minh địa chỉ chuyển tiếp, thì địa chỉ đó sẽ được trả về với trạng thái pending. Thư xác minh sẽ tự động được gửi đến địa chỉ email đích. Chủ sở hữu địa chỉ email phải hoàn tất quy trình xác minh trước khi có thể sử dụng địa chỉ đó.

Những địa chỉ chuyển tiếp không yêu cầu xác minh sẽ có trạng thái xác minh là accepted.

Bật tính năng tự động chuyển tiếp

Gọi phương thức updateAutoForwarding để bật tính năng tự động chuyển tiếp cho một tài khoản. Cuộc gọi yêu cầu cả địa chỉ chuyển tiếp đã đăng ký và đã xác minh, cũng như hành động để thực hiện đối với các tin nhắn được chuyển tiếp.

Ví dụ: để bật tính năng tự động chuyển tiếp và chuyển thư đã chuyển tiếp vào thùng rác, hãy làm như sau:

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 snippet/enable_Forward.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()

Để tắt tính năng tự động chuyển tiếp, hãy gọi updateAutoForwarding và đặt thuộc tính enabled thành false.

Chuyển tiếp các tin nhắn cụ thể

Tính năng tự động chuyển tiếp sẽ gửi tất cả thư đã nhận đến tài khoản đích. Để chuyển tiếp tin nhắn một cách có chọn lọc, hãy dùng bộ lọc để tạo quy tắc chuyển tiếp để phản hồi nội dung hoặc thuộc tính của tin nhắn.