مدیریت فوروارد کردن ایمیل

این سند نحوه پیکربندی ارسال ایمیل در Gmail API را توضیح می‌دهد.

شما می‌توانید از منبع settings برای پیکربندی فوروارد کردن یک حساب کاربری استفاده کنید. برای اینکه یک آدرس ایمیل به عنوان آدرس ایمیل فوروارد شده استفاده شود، باید یکی از معیارهای زیر را داشته باشد:

  • آدرس ایمیل تأیید شده است. برای اطلاعات بیشتر، به ایجاد و تأیید آدرس‌های ارسال مراجعه کنید.
  • آدرس ایمیل متعلق به همان دامنه‌ای است که فرستنده در آن قرار دارد.
  • آدرس ایمیل متعلق به یک زیر دامنه در همان دامنه فرستنده است.
  • آدرس ایمیل متعلق به یک نام مستعار دامنه است که به عنوان بخشی از همان حساب Google Workspace پیکربندی شده است.

اگر آدرس ایمیل فوروارد شده یکی از این قوانین را رعایت نکند، تنظیم فوروارد کردن با استفاده از API با شکست مواجه می‌شود.

برای کسب اطلاعات در مورد نحوه ایجاد ، فهرست کردن ، دریافت یا حذف آدرس‌های ارسال، به روش‌های موجود در منبع settings.forwardingAddresses مراجعه کنید.

برای اطلاعات در مورد نحوه دریافت یا به‌روزرسانی تنظیمات ارسال خودکار، به روش‌های موجود در منبع settings مراجعه کنید.

ایجاد و تأیید آدرس‌های ارسال

قبل از استفاده از آدرس‌های ارسال، باید آنها را ایجاد کنید . در برخی موارد، کاربران باید مالکیت آدرس را نیز تأیید کنند.

اگر جیمیل برای آدرس ارسالی نیاز به تأیید کاربر داشته باشد، آدرس با VerificationStatus در pending برگردانده می‌شود. یک پیام تأیید به طور خودکار به آدرس ایمیل هدف ارسال می‌شود. مالک آدرس ایمیل باید قبل از استفاده، فرآیند تأیید را تکمیل کند.

آدرس‌های ارسالی که نیازی به تأیید ندارند، وضعیت تأییدشان accepted است.

فعال کردن فوروارد خودکار

می‌توانید انتخاب کنید که تمام پیام‌های جدیدتان به آدرس ایمیل دیگری ارسال شوند.

برای انجام این کار، متد updateAutoForwarding را فراخوانی کنید تا ارسال خودکار برای یک حساب کاربری فعال شود. این فراخوانی نیاز به یک آدرس ارسال ثبت شده و تأیید شده و یک اقدام برای انجام پیام‌های ارسال شده دارد. این موارد با استفاده از شیء AutoForwarding تنظیم می‌شوند.

فیلد disposition برای تنظیم وضعیت پیام پس از ارسال پیام استفاده می‌شود. مقدار پیش‌فرض dispositionUnspecified است، اما شما نمی‌توانید این فیلد را روی dispositionUnspecified تنظیم کنید.

نمونه‌های کد زیر نحوه فعال کردن ارسال خودکار و سپس انتقال پیام‌های ارسال شده به سطل زباله را نشان می‌دهند:

جاوا

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;
  }
}

پایتون

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 تنظیم کنید.

پیام‌های خاص را فوروارد کنید

فوروارد خودکار، تمام پیام‌های دریافتی جیمیل را به حساب هدف ارسال می‌کند. برای فوروارد کردن پیام‌های خاص، فیلتری تنظیم کنید تا قوانینی ایجاد شود که پیام‌ها را در پاسخ به ویژگی‌ها یا محتوای پیام فوروارد کند.

برای فوروارد کردن پیام‌ها به چندین حساب، برای هر آدرس ایمیل فوروارد شده یک فیلتر ایجاد کنید.