จัดการการส่งต่ออีเมล

เอกสารนี้อธิบายวิธีกำหนดค่าการส่งต่ออีเมลใน Gmail API

คุณสามารถใช้แหล่งข้อมูล settings เพื่อ กำหนดค่าการส่งต่อสำหรับบัญชี อีเมลที่จะใช้เป็น อีเมลสำหรับการส่งต่อต้องเป็นไปตามเกณฑ์ใดเกณฑ์หนึ่งต่อไปนี้

  • อีเมลได้รับการยืนยันแล้ว ดูข้อมูลเพิ่มเติมได้ที่หัวข้อสร้างและยืนยัน ที่อยู่อีเมลสำหรับการส่งต่อ
  • อีเมลอยู่ในโดเมนเดียวกับผู้ส่ง
  • อีเมลเป็นของโดเมนย่อยภายในโดเมนเดียวกันของผู้ส่ง
  • อีเมลเป็นของชื่อแทนโดเมนที่กำหนดค่าเป็นส่วนหนึ่งของบัญชี Google Workspace เดียวกัน

หากอีเมลสำหรับการส่งต่อไม่เป็นไปตามกฎข้อใดข้อหนึ่งเหล่านี้ การตั้งค่า การส่งต่อโดยใช้ API จะล้มเหลว

ดูข้อมูลเกี่ยวกับวิธี สร้าง แสดง รับ หรือ ลบ อีเมลที่ส่งต่อได้ที่วิธีการในแหล่งข้อมูล settings.forwardingAddresses

ดูข้อมูลเกี่ยวกับวิธี รับ หรือ อัปเดต การตั้งค่าการส่งต่ออัตโนมัติได้ที่วิธีการในแหล่งข้อมูล settings

สร้างและยืนยันอีเมลสำหรับการส่งต่อ

คุณต้อง สร้าง ที่อยู่อีเมลสำหรับการส่งต่อก่อนที่จะใช้งาน ในบางกรณี ผู้ใช้ต้องยืนยัน ความเป็นเจ้าของที่อยู่ด้วย

หาก Gmail กำหนดให้ผู้ใช้ยืนยันอีเมลสำหรับส่งต่อ ระบบจะส่งคืนอีเมลพร้อมกับ VerificationStatus ของ pending ระบบจะส่งข้อความยืนยันไปยังอีเมลปลายทางโดยอัตโนมัติ เจ้าของอีเมลต้องดำเนินการยืนยันให้เสร็จสมบูรณ์ก่อนจึงจะใช้อีเมลได้

ที่อยู่อีเมลสำหรับการส่งต่อที่ไม่ต้องมีการยืนยันจะมีสถานะการยืนยัน เป็น 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 และตั้งค่าฟิลด์ enabled ในออบเจ็กต์ AutoForwarding เป็น false

ส่งต่อข้อความที่ต้องการ

การส่งต่ออัตโนมัติจะส่งข้อความ Gmail ที่ได้รับทั้งหมดไปยังบัญชีเป้าหมาย หากต้องการส่งต่อข้อความที่เฉพาะเจาะจง ให้ตั้งค่าตัวกรองเพื่อสร้างกฎที่ ส่งต่อข้อความเพื่อตอบสนองต่อแอตทริบิวต์หรือเนื้อหาของข้อความ

หากต้องการส่งต่อข้อความไปยังหลายบัญชี ให้สร้างตัวกรองสำหรับอีเมล ที่ใช้ส่งต่อทุกบัญชี