管理别名

“用以下地址发送邮件”别名表示账号可以访问的电子邮件地址 发件人。每个账号始终至少有一个别名 该账号的主电子邮件地址

“用以下地址发送邮件”别名对应于 “用以下地址发送邮件”功能 网页界面

别名还可用于管理账号的签名。基本了解 您必须有 的“用以下地址发送邮件”别名,才能更改电子邮件签名。 上面的视频展示了如何遍历“用以下地址发送邮件”别名,以及如何修改 为用户的主电子邮件地址添加签名。

有关如何使用 createlistgetupdate、 或删除别名, 请参阅 SendAs 参考文档

创建和验证别名

您必须创建 别名。在某些情况下,用户还必须验证对 别名。

如果 Gmail 要求对别名进行用户验证,则该别名将随 状态为 pending。系统会自动向 目标电子邮件地址。电子邮件地址的所有者必须完成验证 然后才能使用它。

不需要验证的别名的验证状态为 accepted

使用 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 fragment/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()