ניהול העברת אימייל

במאמר הזה מוסבר איך להגדיר העברת אימיילים ב-Gmail API.

אתם יכולים להשתמש במשאב settings כדי להגדיר העברה לחשבון. כדי להשתמש בכתובת אימייל להעברה, היא צריכה לעמוד באחד מהקריטריונים הבאים:

  • כתובת האימייל מאומתת. מידע נוסף מופיע במאמר בנושא יצירה ואימות של כתובות להעברה.
  • כתובת האימייל שייכת לאותו דומיין כמו השולח.
  • כתובת האימייל שייכת לתת-דומיין באותו דומיין של השולח.
  • כתובת האימייל שייכת לכתובת אימייל חלופית לדומיין שהוגדרה כחלק מאותו חשבון Google Workspace.

אם כתובת האימייל להעברה לא עומדת באחד מהכללים האלה, הגדרת ההעברה באמצעות ה-API תיכשל.

מידע על יצירה, הצגה, קבלת או מחיקה של כתובות להעברה אוטומטית זמין בשיטות של מקור settings.forwardingAddresses.

במשאב settings מוסבר איך מקבלים או מעדכנים את הגדרות ההעברה האוטומטית.

יצירה ואימות של כתובות להעברה

כדי להשתמש בכתובות להעברה, צריך ליצור אותן. במקרים מסוימים, המשתמשים צריכים גם לאמת את הבעלות על הכתובת.

אם Gmail דורש אימות משתמש עבור כתובת להעברה, ה-API מחזיר את הכתובת עם VerificationStatus של pending. ‫Gmail שולח באופן אוטומטי הודעת אימות לכתובת האימייל של היעד. הבעלים של כתובת האימייל צריך להשלים את תהליך האימות כדי שתוכלו להשתמש בה.

כתובות להעברה שלא דורשות אימות מקבלות את סטטוס האימות 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()

כדי להשבית את ההעברה האוטומטית, צריך לבצע קריאה ל-method‏ updateAutoForwarding ולהגדיר את השדה enabled באובייקט AutoForwarding לערך false.

העברת הודעות ספציפיות

העברה אוטומטית שולחת את כל ההודעות שמתקבלות ב-Gmail לחשבון היעד. כדי להעביר הודעות ספציפיות, צריך להגדיר מסנן כדי ליצור כללים להעברת הודעות בתגובה למאפיינים או לתוכן של ההודעות.

כדי להעביר הודעות לכמה חשבונות, יוצרים מסנן לכל אחת מכתובות האימייל להעברה.