Quản lý chế độ cài đặt khi đi nghỉ bằng Gmail API

Tài liệu này giải thích cách sử dụng tính năng thư trả lời tự động trong API Gmail.

Bạn có thể sử dụng tài nguyên settings để thiết lập thư trả lời tự động cho một tài khoản.

Để biết thông tin về cách nhận hoặc cập nhật chế độ cài đặt thư trả lời tự động khi đi vắng, hãy xem tài nguyên settings.

Định cấu hình tính năng trả lời tự động

Thư trả lời tự động yêu cầu phải có tiêu đề và nội dung phản hồi ở định dạng HTML hoặc văn bản thuần tuý. Các chế độ cài đặt này được đặt bằng cách sử dụng đối tượng VacationSettings. Bạn có thể bật tính năng trả lời tự động vô thời hạn hoặc giới hạn trong một khoảng thời gian cụ thể. Bạn cũng có thể hạn chế tính năng trả lời tự động chỉ cho những người liên hệ đã biết hoặc thành viên trong miền.

Các đoạn mã sau đây cho biết cách thiết lập thư trả lời tự động trong một khoảng thời gian cố định và hạn chế thư trả lời cho người dùng trong cùng một miền:

Java

gmail/snippets/src/main/java/EnableAutoReply.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.VacationSettings;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

/* Class to demonstrate the use of Gmail Enable Auto Reply API*/
public class EnableAutoReply {
  /**
   * Enables the auto reply
   *
   * @return the reply message and response metadata.
   * @throws IOException - if service account credentials file not found.
   */
  public static VacationSettings autoReply() 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_BASIC);
    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 reply by restricting domain with start time and end time
      VacationSettings vacationSettings = new VacationSettings()
          .setEnableAutoReply(true)
          .setResponseBodyHtml(
              "I am on vacation and will reply when I am back in the office. Thanks!")
          .setRestrictToDomain(true)
          .setStartTime(LocalDateTime.now()
              .toEpochSecond(ZoneOffset.from(ZonedDateTime.now())) * 1000)
          .setEndTime(LocalDateTime.now().plusDays(7)
              .toEpochSecond(ZoneOffset.from(ZonedDateTime.now())) * 1000);

      VacationSettings response = service.users().settings()
          .updateVacation("me", vacationSettings).execute();
      // Prints the auto-reply response body
      System.out.println("Enabled auto reply with message : " + response.getResponseBodyHtml());
      return response;
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      GoogleJsonError error = e.getDetails();
      if (error.getCode() == 403) {
        System.err.println("Unable to enable auto reply: " + e.getDetails());
      } else {
        throw e;
      }
    }
    return null;
  }
}

Python

gmail/snippet/settings snippets/enable_auto_reply.py
from datetime import datetime, timedelta

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from numpy import long


def enable_auto_reply():
  """Enable auto reply.
  Returns:Draft object, including reply message and response 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)

    epoch = datetime.utcfromtimestamp(0)
    now = datetime.now()
    start_time = (now - epoch).total_seconds() * 1000
    end_time = (now + timedelta(days=7) - epoch).total_seconds() * 1000
    vacation_settings = {
        "enableAutoReply": True,
        "responseBodyHtml": (
            "I am on vacation and will reply when I am "
            "back in the office. Thanks!"
        ),
        "restrictToDomain": True,
        "startTime": long(start_time),
        "endTime": long(end_time),
    }

    # pylint: disable=E1101
    response = (
        service.users()
        .settings()
        .updateVacation(userId="me", body=vacation_settings)
        .execute()
    )
    print(f"Enabled AutoReply with message: {response.get('responseBodyHtml')}")

  except HttpError as error:
    print(f"An error occurred: {error}")
    response = None

  return response


if __name__ == "__main__":
  enable_auto_reply()

Để tắt tính năng trả lời tự động, hãy gọi phương thức settings.updateVacation và đặt trường enableAutoReply trên đối tượng VacationSettings thành false. Nếu bạn đặt giá trị endTime, thì tính năng trả lời tự động sẽ bị tắt sau khi thời gian đã chỉ định trôi qua.