下書きを使用する
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
下書きは、DRAFT
システムラベルが適用された未送信のメッセージを表します。作成した下書き内のメッセージは編集できませんが、置き換えることはできます。この意味で、下書きリソースは、基盤となるメッセージ ID がメッセージの置き換えごとに変更されるため、安定した ID を提供する単なるコンテナです。
下書き内のメッセージ リソースは、他のメッセージと同様の動作をしますが、次の点が異なります。
- 下書きメッセージには、
DRAFT
システムラベル以外のラベルを付けることはできません。
- 下書きを送信すると、下書きは自動的に削除され、更新された ID を含む新しいメッセージが
SENT
システムラベルとともに作成されます。このメッセージは drafts.send
レスポンスで返されます。
目次
下書きメッセージを作成する
アプリケーションは、drafts.create メソッドを使用して下書きを作成できます。一般的なプロセスは次のとおりです。
- RFC 2822 に準拠した MIME メッセージを作成します。
- メッセージを base64url でエンコードされた文字列に変換します。
- 下書きを作成し、
drafts.message.raw
フィールドの値をエンコードされた文字列に設定します。
次のコード例は、このプロセスを示しています。
下書きを更新する
下書きの作成と同様に、下書きを更新するには、リクエストの本文で Draft
リソースを指定し、draft.message.raw
フィールドを MIME メッセージを含む base64url でエンコードされた文字列に設定する必要があります。メッセージは更新できないため、下書きに含まれるメッセージは破棄され、更新リクエストで指定された新しい MIME メッセージに置き換えられます。
下書きに含まれる現在の MIME メッセージを取得するには、パラメータ format=raw
を指定して drafts.get
を呼び出します。
詳細については、drafts.update
をご覧ください。
下書きの送信
下書きを送信する際に、メッセージをそのまま送信するか、更新したメッセージとして送信するかを選択できます。新しいメッセージで下書きコンテンツを更新する場合は、drafts.send
リクエストの本文で Draft
リソースを指定し、送信する下書きの draft.id
を設定し、draft.message.raw
フィールドを base64url エンコード文字列としてエンコードされた新しい MIME メッセージに設定します。詳細については、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)."]]