使用草稿
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
草稿是指应用了 DRAFT
系统标签的未发送消息。
草稿中的消息一经创建便无法修改,但可以替换。从这个意义上讲,草稿资源只是一个容器,它提供稳定的 ID,因为底层消息 ID 会在每次替换消息时发生变化。
草稿中的消息资源与其他消息的行为类似,但存在以下差异:
- 草稿邮件不能有除
DRAFT
系统标签以外的任何标签。
- 发送草稿后,系统会自动删除该草稿,并创建一个带有
SENT
系统标签的新邮件,其中包含更新后的 ID。此消息在 drafts.send
响应中返回。
目录
创建邮件草稿
您的应用可以使用 drafts.create 方法创建草稿。一般流程如下:
- 创建符合 RFC 2822 的 MIME 消息。
- 将消息转换为 base64url 编码的字符串。
- 创建草稿,并将
drafts.message.raw
字段的值设置为编码后的字符串。
以下代码示例演示了此过程。
更新草稿
与创建草稿类似,如需更新草稿,您必须在请求正文中提供 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
。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-01。
[null,null,["最后更新时间 (UTC):2025-08-01。"],[],[],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)."]]