使用草稿

草稿代表带有 DRAFT 系统标签的未发送邮件。 草稿中包含的消息一经创建便无法修改,但此草稿 可以替换。从这个意义上讲, draft resource 只是一个容器 ,因为底层消息 ID 每次都会发生变化,因此能够提供稳定的 ID 消息会被替换。

草稿中的邮件/消息资源 的行为与其他消息类似,但存在以下差异:

  • 草稿邮件不能包含 DRAFT 系统标签以外的任何标签。
  • 草稿发送后,草稿会被自动删除,并且会有一条新消息 具有 SENT 系统标签的新 ID 创建。此消息为 在 drafts.send 中返回 响应。

目录

正在创建消息草稿

您的应用可以使用 drafts.create 方法的。通过 一般流程是:

  1. 创建符合以下要求的 MIME 消息: RFC 2822
  2. 将消息转换为 base64url 编码的字符串。
  3. 创建草稿,设置 drafts.message.raw 字段的值设置为编码字符串。

以下代码示例演示了该过程。

Java

gmail/snippets/src/main/java/CreateDraft.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.Draft;
import com.google.api.services.gmail.model.Message;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.codec.binary.Base64;

/* Class to demonstrate the use of Gmail Create Draft API */
public class CreateDraft {
  /**
   * Create a draft email.
   *
   * @param fromEmailAddress - Email address to appear in the from: header
   * @param toEmailAddress   - Email address of the recipient
   * @return the created draft, {@code null} otherwise.
   * @throws MessagingException - if a wrongly formatted address is encountered.
   * @throws IOException        - if service account credentials file not found.
   */
  public static Draft createDraftMessage(String fromEmailAddress,
                                         String toEmailAddress)
      throws MessagingException, 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_COMPOSE);
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);

    // Create the gmail API client
    Gmail service = new Gmail.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Gmail samples")
        .build();

    // Create the email content
    String messageSubject = "Test message";
    String bodyText = "lorem ipsum.";

    // Encode as MIME message
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage email = new MimeMessage(session);
    email.setFrom(new InternetAddress(fromEmailAddress));
    email.addRecipient(javax.mail.Message.RecipientType.TO,
        new InternetAddress(toEmailAddress));
    email.setSubject(messageSubject);
    email.setText(bodyText);

    // Encode and wrap the MIME message into a gmail message
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    email.writeTo(buffer);
    byte[] rawMessageBytes = buffer.toByteArray();
    String encodedEmail = Base64.encodeBase64URLSafeString(rawMessageBytes);
    Message message = new Message();
    message.setRaw(encodedEmail);

    try {
      // Create the draft message
      Draft draft = new Draft();
      draft.setMessage(message);
      draft = service.users().drafts().create("me", draft).execute();
      System.out.println("Draft id: " + draft.getId());
      System.out.println(draft.toPrettyString());
      return draft;
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      GoogleJsonError error = e.getDetails();
      if (error.getCode() == 403) {
        System.err.println("Unable to create draft: " + e.getMessage());
      } else {
        throw e;
      }
    }
    return null;
  }
}

Python

gmail/snippet/send mail/create_draft.py
import base64
from email.message import EmailMessage

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


def gmail_create_draft():
  """Create and insert a draft email.
   Print the returned draft's message and id.
   Returns: Draft object, including draft id and message 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)

    message = EmailMessage()

    message.set_content("This is automated draft mail")

    message["To"] = "gduser1@workspacesamples.dev"
    message["From"] = "gduser2@workspacesamples.dev"
    message["Subject"] = "Automated draft"

    # encoded message
    encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()

    create_message = {"message": {"raw": encoded_message}}
    # pylint: disable=E1101
    draft = (
        service.users()
        .drafts()
        .create(userId="me", body=create_message)
        .execute()
    )

    print(f'Draft id: {draft["id"]}\nDraft message: {draft["message"]}')

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

  return draft


if __name__ == "__main__":
  gmail_create_draft()

正在更新草稿

与创建草稿类似,如需更新草稿,您必须提供 Draft 并在请求正文中包含 draft.message.raw 字段 设置为包含 MIME 消息的 base64url 编码字符串。因为 条讯息无法更新,草稿中包含的邮件被销毁 并替换为更新请求中提供的新 MIME 消息。

您可以检索草稿中包含的当前 MIME 邮件,只需调用 带有参数的 drafts.get format=raw

如需了解详情,请参阅 drafts.update

正在发送草稿

发送草稿时,您可以选择按原样发送邮件,或使用 已更新的消息。如果您要使用新消息更新草稿内容, 在Draft drafts.send 请求;设这个 要发送的草稿的 draft.id;并将 draft.message.raw 字段设为 编码为 base64url 编码字符串的新 MIME 消息。有关 相关信息,请参阅 drafts.send