Làm việc với bản nháp

Bản nháp biểu thị các thư chưa được gửi có áp dụng nhãn hệ thống DRAFT. Bạn không thể chỉnh sửa thông báo có trong bản nháp sau khi tạo, nhưng có thể thay thế thông báo đó. Theo nghĩa này, tài nguyên nháp chỉ đơn giản là một vùng chứa cung cấp mã nhận dạng ổn định vì mã nhận dạng thông báo cơ bản thay đổi mỗi khi thông báo được thay thế.

Tài nguyên thông báo bên trong một bản nháp có hành vi tương tự như các thông báo khác, ngoại trừ những điểm khác biệt sau:

  • Thư nháp không được có bất kỳ nhãn nào khác ngoài nhãn hệ thống DRAFT.
  • Khi được gửi đi, bản nháp sẽ tự động bị xoá và một thư mới có mã nhận dạng đã cập nhật sẽ được tạo có nhãn hệ thống SENT. Thông báo này được trả về trong phản hồi drafts.send.

Nội dung

Tạo tin nhắn nháp

Ứng dụng của bạn có thể tạo bản nháp bằng phương thức drafts.create. Quy trình chung là:

  1. Tạo thông báo MIME tuân thủ RFC 2822.
  2. Chuyển đổi thông báo thành chuỗi mã hoá base64url.
  3. Tạo bản nháp, đặt giá trị của trường drafts.message.raw thành chuỗi đã mã hoá.

Các ví dụ về mã sau đây minh hoạ quy trình.

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 thư/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()

Đang cập nhật các bản nháp

Tương tự như việc tạo một bản nháp, để cập nhật một bản nháp, bạn phải cung cấp tài nguyên Draft trong phần nội dung yêu cầu với trường draft.message.raw được đặt thành một chuỗi được mã hoá base64url chứa thông báo MIME. Vì không thể cập nhật thông báo nên thông báo chứa trong bản nháp sẽ bị huỷ và thay thế bằng thông báo MIME mới được cung cấp trong yêu cầu cập nhật.

Bạn có thể truy xuất thông báo MIME hiện tại có trong bản nháp bằng cách gọi drafts.get với tham số format=raw.

Để biết thêm thông tin, hãy xem drafts.update.

Gửi thư nháp

Khi gửi thư nháp, bạn có thể chọn gửi nguyên trạng hoặc gửi thư nháp với tin nhắn đã cập nhật. Nếu bạn đang cập nhật nội dung nháp bằng một thông báo mới, hãy cung cấp tài nguyên Draft trong phần nội dung của yêu cầu drafts.send; thiết lập draft.id của bản nháp sẽ được gửi; và đặt trường draft.message.raw thành thông báo MIME mới được mã hoá dưới dạng chuỗi được mã hoá base64url. Để biết thêm thông tin, hãy xem drafts.send.