使用 Gmail API 管理別名和簽名

本文說明如何在 Gmail API 中設定「以別名傳送郵件」和電子郵件簽名。

「以別名傳送」別名代表帳戶可從中傳送郵件的電子郵件地址。每個帳戶至少都有一個別名,代表帳戶的主要電子郵件地址。

寄件者身分別名對應於 Gmail 網頁介面的「選擇寄件地址」功能。

您也可以使用別名管理帳戶的簽名。如要變更電子郵件簽名,您必須對「以別名傳送」有基本瞭解。

如要瞭解如何建立列出取得更新刪除別名,請參閱 settings.sendAs 資源。

建立及驗證別名

您必須先建立別名,才能使用別名。在某些情況下,使用者也必須驗證別名的擁有權。

如果 Gmail 要求別名通過使用者驗證,API 會傳回別名,並在其中加入 VerificationStatus pending。Gmail 會自動將驗證訊息傳送到目標電子郵件地址。電子郵件地址擁有者必須先完成驗證程序,才能使用別名。

不需要驗證的別名會顯示 accepted 驗證狀態。

如有需要,請使用 settings.sendAs.verify 方法重新傳送驗證要求。

SMTP 設定

外部地址的別名應透過遠端 SMTP 郵件提交代理程式 (MSA) 傳送郵件。如要為別名設定 SMTP MSA,請使用 smtpMsa 欄位提供連線詳細資料。

管理簽名

您也可以為每個別名設定電子郵件簽名。下列程式碼範例說明如何為使用者的主要地址設定簽名:

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 snippets/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()