Quản lý email đại diện

Email đại diện được gửi bằng địa chỉ email mà một tài khoản có thể dùng để gửi thư. Mỗi tài khoản luôn có ít nhất một email đại diện đại diện cho địa chỉ email chính của tài khoản.

Bí danh gửi bằng địa chỉ tương ứng với tính năng"Gửi thư bằng địa chỉ" trong giao diện web.

Email đại diện cũng được dùng để quản lý chữ ký cho một tài khoản. Bạn cần có những hiểu biết cơ bản về email đại diện gửi bằng địa chỉ để có thể thay đổi chữ ký email. Video ở trên cho bạn biết cách lặp lại thông qua email đại diện gửi bằng địa chỉ và sửa đổi chữ ký cho địa chỉ email chính của người dùng.

Để biết thông tin về cách tạo, danh sách, nhận, cập nhật hoặc xoá các bí danh, hãy xem tài liệu tham khảo SendAs.

Tạo và xác minh bí danh

Bạn phải tạo bí danh 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 bí danh.

Nếu Gmail yêu cầu người dùng xác minh cho một bí danh, thì bí danh sẽ được trả về với trạng thái pending. Thông báo 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ỉ email.

Bí danh không yêu cầu xác minh sẽ có trạng thái xác minh là accepted.

Sử dụng phương thức xác minh để gửi lại yêu cầu xác minh nếu cần.

Cài đặt SMTP

Email đại diện cho các địa chỉ bên ngoài sẽ gửi thư thông qua một tác nhân gửi thư SMTP (MSA) từ xa. Để định cấu hình SMTP MSA cho một bí danh, hãy sử dụng trường smtpMsa để cung cấp thông tin chi tiết về kết nối.

Quản lý chữ ký

Bạn cũng có thể định cấu hình chữ ký email cho từng email đại diện. Ví dụ: để đặt chữ ký cho địa chỉ chính của người dùng:

Java

gmail/snippets/src/main/java/UpdateSignature.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.ListSendAsResponse;
import com.google.api.services.gmail.model.SendAs;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;

/* Class to demonstrate the use of Gmail Update Signature API */
public class UpdateSignature {
  /**
   * Update the gmail signature.
   *
   * @return the updated signature id , {@code null} otherwise.
   * @throws IOException - if service account credentials file not found.
   */
  public static String updateGmailSignature() 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 {
      SendAs primaryAlias = null;
      ListSendAsResponse aliases = service.users().settings().sendAs().list("me").execute();
      for (SendAs alias : aliases.getSendAs()) {
        if (alias.getIsPrimary()) {
          primaryAlias = alias;
          break;
        }
      }
      // Updating a new signature
      SendAs aliasSettings = new SendAs().setSignature("Automated Signature");
      SendAs result = service.users().settings().sendAs().patch(
              "me",
              primaryAlias.getSendAsEmail(),
              aliasSettings)
          .execute();
      //Prints the updated signature
      System.out.println("Updated signature - " + result.getSignature());
      return result.getSignature();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      GoogleJsonError error = e.getDetails();
      if (error.getCode() == 403) {
        System.err.println("Unable to update signature: " + e.getDetails());
      } else {
        throw e;
      }
    }
    return null;
  }
}

Python

gmail/snippet/settings snippet/update_signature.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def update_signature():
  """Create and update signature in gmail.
  Returns:Draft object, including updated signature.

  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)

    primary_alias = None

    # pylint: disable=E1101
    aliases = service.users().settings().sendAs().list(userId="me").execute()
    for alias in aliases.get("sendAs"):
      if alias.get("isPrimary"):
        primary_alias = alias
        break

    send_as_configuration = {
        "displayName": primary_alias.get("sendAsEmail"),
        "signature": "Automated Signature",
    }

    # pylint: disable=E1101
    result = (
        service.users()
        .settings()
        .sendAs()
        .patch(
            userId="me",
            sendAsEmail=primary_alias.get("sendAsEmail"),
            body=send_as_configuration,
        )
        .execute()
    )
    print(f'Updated signature for: {result.get("displayName")}')

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

  return result.get("signature")


if __name__ == "__main__":
  update_signature()