Tạo và gửi email nháp

Tài liệu này giải thích cách tạo, cập nhật và gửi email nháp bằng Gmail API.

Thư nháp là những thư chưa gửi và được áp dụng nhãn hệ thống DRAFT. Bạn không thể chỉnh sửa nội dung trong bản nháp sau khi tạo, nhưng có thể thay thế nội dung đó. Theo nghĩa này, tài nguyên drafts 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 sẽ thay đổi mỗi khi thông báo được thay thế.

Tài nguyên messages trong 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ó nhãn nào khác ngoài nhãn hệ thống DRAFT.
  • Khi bản nháp được gửi, bản nháp sẽ tự động bị xoá và một thư mới có mã nhận dạng mới sẽ được tạo bằng nhãn hệ thống SENT. Thông báo này được trả về trong phản hồi phương thức drafts.send.

Tạo bả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. Cách tạo bản nháp:

  1. Tạo một thư MIME tuân thủ RFC 2822.
  2. Chuyển đổi thông báo thành một chuỗi được mã hoá base64URL.
  3. Gọi phương thức drafts.create, đặt giá trị của trường messages.raw thành chuỗi được mã hoá.

Các mẫu mã sau đây minh hoạ quy trình này:

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

cURL

curl --request POST \
  'https://gmail.googleapis.com/gmail/v1/users/me/drafts' \
  --header 'Authorization: Bearer ACCESS_TOKEN" \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"message":{"raw":"MESSAGE"}}'

Thay thế nội dung sau:

  • ACCESS_TOKEN: mã truy cập cấp quyền truy cập vào API.
  • MESSAGE: thông báo MIME được định dạng RFC 2822, được mã hoá dưới dạng base64URL.

Cập nhật bản nháp

Tương tự như việc tạo bản nháp, để cập nhật bản nháp, bạn phải cung cấp một tài nguyên drafts trong nội dung yêu cầu của mình với trường messages.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ư nên thư có trong thư nháp sẽ bị xoá và thay thế bằng thư 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 phương thức drafts.get bằng tham số truy vấn format=raw.

Để biết thêm thông tin, hãy xem phương thức drafts.update.

Gửi bản nháp

Khi gửi bản nháp, bạn có thể gửi nguyên trạng hoặc cung cấp thông tin cập nhật trong yêu cầu gửi.

Để cập nhật bản nháp khi gửi, hãy cung cấp tài nguyên drafts trong nội dung yêu cầu của phương thức drafts.send. Trong tài nguyên drafts, bạn phải chỉ định bản nháp id của bản nháp sẽ được gửi và đặt trường messages.raw thành thông báo MIME mới được mã hoá dưới dạng chuỗi base64URL.

Để biết thông tin về cách gửi thư trong Gmail, hãy xem bài viết Gửi thư.