使用草稿

草稿代表已套用 DRAFT 系統標籤的未傳送郵件。草稿內含的訊息一旦建立就無法編輯,但可以取代。在這種情況下,草稿資源只是提供穩定 ID 的容器,因為每次取代訊息時,基礎訊息 ID 都會變更。

草稿中的訊息資源行為與其他訊息類似,但有以下差異:

  • 草稿訊息只能使用 DRAFT 系統標籤。
  • 草稿傳送後,系統會自動刪除草稿,並使用 SENT 系統標籤建立具有更新 ID 的新訊息。這則訊息會在 drafts.send 回應中傳回。

目錄

建立郵件草稿

應用程式可以使用 drafts.create 方法建立草稿。一般程序如下:

  1. 建立符合 RFC 2822 的 MIME 訊息。
  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 郵件取代。

您可以呼叫 drafts.get 並傳入 format=raw 參數,藉此擷取草稿中目前的 MIME 訊息。

詳情請參閱 drafts.update

傳送草稿

傳送草稿時,您可以選擇傳送原始訊息,或是傳送更新後的訊息。如果您要使用新訊息更新草稿內容,請在 drafts.send 要求的主體中提供 Draft 資源;設定要傳送草稿的 draft.id;並將 draft.message.raw 欄位設為以 base64url 編碼字串編碼的新 MIME 訊息。詳情請參閱 drafts.send