การใช้งานฉบับร่าง
จัดทุกอย่างให้เป็นระเบียบอยู่เสมอด้วยคอลเล็กชัน
บันทึกและจัดหมวดหมู่เนื้อหาตามค่ากำหนดของคุณ
ข้อความร่างคือข้อความที่ยังไม่ได้ส่งซึ่งมีป้ายกำกับระบบ DRAFT
เมื่อสร้างข้อความในฉบับร่างแล้วจะแก้ไขไม่ได้ แต่สามารถแทนที่ได้ ในแง่นี้ ทรัพยากรฉบับร่างเป็นเพียงคอนเทนเนอร์
ที่ให้รหัสที่เสถียรเนื่องจากรหัสข้อความพื้นฐานจะเปลี่ยนทุกครั้ง
ที่มีการแทนที่ข้อความ
ทรัพยากรข้อความภายในฉบับร่าง
มีลักษณะการทำงานคล้ายกับข้อความอื่นๆ ยกเว้นความแตกต่างต่อไปนี้
- ข้อความฉบับร่างต้องไม่มีป้ายกำกับอื่นใดนอกเหนือจากป้ายกำกับระบบ
DRAFT
- เมื่อส่งฉบับร่าง ระบบจะลบฉบับร่างโดยอัตโนมัติและสร้างข้อความใหม่
พร้อมรหัสที่อัปเดตโดยใช้
SENT
ป้ายกำกับของระบบ ข้อความนี้จะแสดงในคำตอบของ drafts.send
เนื้อหา
การสร้างข้อความร่าง
แอปพลิเคชันของคุณสร้างฉบับร่างได้โดยใช้เมธอด drafts.create
กระบวนการทั่วไปมีดังนี้
- สร้างข้อความ MIME ที่เป็นไปตาม RFC 2822
- แปลงข้อความเป็นสตริงที่เข้ารหัส base64url
- สร้างฉบับร่างโดยตั้งค่าฟิลด์
drafts.message.raw
เป็นสตริงที่เข้ารหัส
ตัวอย่างโค้ดต่อไปนี้แสดงกระบวนการ
การอัปเดตฉบับร่าง
เช่นเดียวกับการสร้างฉบับร่าง หากต้องการอัปเดตฉบับร่าง คุณต้องระบุDraft
ทรัพยากรในเนื้อหาของคำขอโดยตั้งค่าฟิลด์draft.message.raw
เป็นสตริงที่เข้ารหัส base64url ซึ่งมีข้อความ MIME เนื่องจากอัปเดตข้อความไม่ได้ ระบบจึงทำลายข้อความในฉบับร่าง
และแทนที่ด้วยข้อความ MIME ใหม่ที่ระบุในคำขออัปเดต
คุณสามารถดึงข้อความ MIME ปัจจุบันที่อยู่ในฉบับร่างได้โดยการเรียกใช้
drafts.get
ด้วยพารามิเตอร์
format=raw
ดูข้อมูลเพิ่มเติมได้ที่
drafts.update
การส่งฉบับร่าง
เมื่อส่งฉบับร่าง คุณเลือกได้ว่าจะส่งข้อความตามเดิมหรือส่งเป็นข้อความที่อัปเดตแล้ว หากคุณกำลังอัปเดตเนื้อหาฉบับร่างด้วยข้อความใหม่ ให้ระบุทรัพยากร Draft
ในเนื้อหาของคำขอ drafts.send
ตั้งค่า draft.id
ของฉบับร่างที่จะส่ง และตั้งค่าฟิลด์ draft.message.raw
เป็นข้อความ MIME ใหม่ที่เข้ารหัสเป็นสตริงที่เข้ารหัส base64url ดูข้อมูลเพิ่มเติมได้ที่ drafts.send
เนื้อหาของหน้าเว็บนี้ได้รับอนุญาตภายใต้ใบอนุญาตที่ต้องระบุที่มาของครีเอทีฟคอมมอนส์ 4.0 และตัวอย่างโค้ดได้รับอนุญาตภายใต้ใบอนุญาต Apache 2.0 เว้นแต่จะระบุไว้เป็นอย่างอื่น โปรดดูรายละเอียดที่นโยบายเว็บไซต์ Google Developers Java เป็นเครื่องหมายการค้าจดทะเบียนของ Oracle และ/หรือบริษัทในเครือ
อัปเดตล่าสุด 2025-08-01 UTC
[null,null,["อัปเดตล่าสุด 2025-08-01 UTC"],[],[],null,["# Working with Drafts\n\nDrafts represent unsent messages with the `DRAFT` system label applied.\nThe message contained within the draft cannot be edited once created, but it\ncan be replaced. In this sense, the\n[draft resource](/workspace/gmail/api/v1/reference/users/drafts) is simply a container\nthat provides a stable ID because the underlying message IDs change every time\nthe message is replaced.\n\n[Message resources](/workspace/gmail/api/v1/reference/users/messages) inside a draft\nhave similar behavior to other messages except for the following differences:\n\n- Draft messages cannot have any label other than the `DRAFT` system label.\n- When the draft is sent, the draft is automatically deleted and a new message with an updated ID is created with the `SENT` system label. This message is returned in the [`drafts.send`](/workspace/gmail/api/v1/reference/users/drafts/send) response.\n\nContents\n--------\n\nCreating draft messages\n-----------------------\n\nYour application can create drafts using the\n[drafts.create](/workspace/gmail/api/v1/reference/users/drafts/create) method. The\ngeneral process is to:\n\n1. Create a MIME message that complies with [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt).\n2. Convert the message to a base64url encoded string.\n3. [Create a draft](/workspace/gmail/api/v1/reference/users/drafts/create), setting the value of the `drafts.message.raw` field to the encoded string.\n\nThe following code examples demonstrate the process. \n\n### Java\n\ngmail/snippets/src/main/java/CreateDraft.java \n[View on GitHub](https://github.com/googleworkspace/java-samples/blob/main/gmail/snippets/src/main/java/CreateDraft.java) \n\n```java\nimport com.google.api.client.googleapis.json.GoogleJsonError;\nimport com.google.api.client.googleapis.json.GoogleJsonResponseException;\nimport com.google.api.client.http.HttpRequestInitializer;\nimport com.google.api.client.http.javanet.NetHttpTransport;\nimport com.google.api.client.json.gson.GsonFactory;\nimport com.google.api.services.gmail.Gmail;\nimport com.google.api.services.gmail.GmailScopes;\nimport com.google.api.services.gmail.model.Draft;\nimport com.google.api.services.gmail.model.Message;\nimport com.google.auth.http.HttpCredentialsAdapter;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.util.Properties;\nimport javax.mail.MessagingException;\nimport javax.mail.Session;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeMessage;\nimport org.apache.commons.codec.binary.Base64;\n\n/* Class to demonstrate the use of Gmail Create Draft API */\npublic class CreateDraft {\n /**\n * Create a draft email.\n *\n * @param fromEmailAddress - Email address to appear in the from: header\n * @param toEmailAddress - Email address of the recipient\n * @return the created draft, {@code null} otherwise.\n * @throws MessagingException - if a wrongly formatted address is encountered.\n * @throws IOException - if service account credentials file not found.\n */\n public static Draft createDraftMessage(String fromEmailAddress,\n String toEmailAddress)\n throws MessagingException, IOException {\n /* Load pre-authorized user credentials from the environment.\n TODO(developer) - See https://developers.google.com/identity for\n guides on implementing OAuth2 for your application.*/\n GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()\n .createScoped(GmailScopes.GMAIL_COMPOSE);\n HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);\n\n // Create the gmail API client\n Gmail service = new Gmail.Builder(new NetHttpTransport(),\n GsonFactory.getDefaultInstance(),\n requestInitializer)\n .setApplicationName(\"Gmail samples\")\n .build();\n\n // Create the email content\n String messageSubject = \"Test message\";\n String bodyText = \"lorem ipsum.\";\n\n // Encode as MIME message\n Properties props = new Properties();\n Session session = Session.getDefaultInstance(props, null);\n MimeMessage email = new MimeMessage(session);\n email.setFrom(new InternetAddress(fromEmailAddress));\n email.addRecipient(javax.mail.Message.RecipientType.TO,\n new InternetAddress(toEmailAddress));\n email.setSubject(messageSubject);\n email.setText(bodyText);\n\n // Encode and wrap the MIME message into a gmail message\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n email.writeTo(buffer);\n byte[] rawMessageBytes = buffer.toByteArray();\n String encodedEmail = Base64.encodeBase64URLSafeString(rawMessageBytes);\n Message message = new Message();\n message.setRaw(encodedEmail);\n\n try {\n // Create the draft message\n Draft draft = new Draft();\n draft.setMessage(message);\n draft = service.users().drafts().create(\"me\", draft).execute();\n System.out.println(\"Draft id: \" + draft.getId());\n System.out.println(draft.toPrettyString());\n return draft;\n } catch (GoogleJsonResponseException e) {\n // TODO(developer) - handle error appropriately\n GoogleJsonError error = e.getDetails();\n if (error.getCode() == 403) {\n System.err.println(\"Unable to create draft: \" + e.getMessage());\n } else {\n throw e;\n }\n }\n return null;\n }\n}\n```\n\n### Python\n\ngmail/snippet/send mail/create_draft.py \n[View on GitHub](https://github.com/googleworkspace/python-samples/blob/main/gmail/snippet/send mail/create_draft.py) \n\n```python\nimport base64\nfrom email.message import EmailMessage\n\nimport google.auth\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\n\ndef gmail_create_draft():\n \"\"\"Create and insert a draft email.\n Print the returned draft's message and id.\n Returns: Draft object, including draft id and message meta data.\n\n Load pre-authorized user credentials from the environment.\n TODO(developer) - See https://developers.google.com/identity\n for guides on implementing OAuth2 for the application.\n \"\"\"\n creds, _ = google.auth.default()\n\n try:\n # create gmail api client\n service = build(\"gmail\", \"v1\", credentials=creds)\n\n message = EmailMessage()\n\n message.set_content(\"This is automated draft mail\")\n\n message[\"To\"] = \"gduser1@workspacesamples.dev\"\n message[\"From\"] = \"gduser2@workspacesamples.dev\"\n message[\"Subject\"] = \"Automated draft\"\n\n # encoded message\n encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()\n\n create_message = {\"message\": {\"raw\": encoded_message}}\n # pylint: disable=E1101\n draft = (\n service.users()\n .drafts()\n .create(userId=\"me\", body=create_message)\n .execute()\n )\n\n print(f'Draft id: {draft[\"id\"]}\\nDraft message: {draft[\"message\"]}')\n\n except HttpError as error:\n print(f\"An error occurred: {error}\")\n draft = None\n\n return draft\n\n\nif __name__ == \"__main__\":\n gmail_create_draft()\n```\n\nUpdating drafts\n---------------\n\nSimilarly to creating a draft, to update a draft you must supply a `Draft`\nresource in the body of your request with the `draft.message.raw` field\nset to a base64url encoded string containing the MIME message. Because\nmessages cannot be updated, the message contained in the draft is destroyed\nand replaced by the new MIME message supplied in the update request.\n\nYou can retrieve the current MIME message contained in the draft by calling\n[`drafts.get`](/workspace/gmail/api/v1/reference/users/drafts/get) with the parameter\n`format=raw`.\n\nFor more information, see\n[`drafts.update`](/workspace/gmail/api/v1/reference/users/drafts/update).\n\nSending drafts\n--------------\n\nWhen sending a draft, you can choose to send the message as-is or as with an\nupdated message. If you are updating the draft content with a new message,\nsupply a `Draft` resource in the body of the\n[`drafts.send`](/workspace/gmail/api/v1/reference/users/drafts/send) request; set the\n`draft.id` of the draft to be sent; and set the `draft.message.raw` field to the\nnew MIME message encoded as a base64url encoded string. For more\ninformation, see [`drafts.send`](/workspace/gmail/api/v1/reference/users/drafts/send)."]]