استخدام المسودات
تنظيم صفحاتك في مجموعات
يمكنك حفظ المحتوى وتصنيفه حسب إعداداتك المفضّلة.
تمثّل المسودات الرسائل غير المُرسَلة التي تم تطبيق تصنيف النظام 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
.
إنّ محتوى هذه الصفحة مرخّص بموجب ترخيص Creative Commons Attribution 4.0 ما لم يُنصّ على خلاف ذلك، ونماذج الرموز مرخّصة بموجب ترخيص Apache 2.0. للاطّلاع على التفاصيل، يُرجى مراجعة سياسات موقع Google Developers. إنّ Java هي علامة تجارية مسجَّلة لشركة Oracle و/أو شركائها التابعين.
تاريخ التعديل الأخير: 2025-08-01 (حسب التوقيت العالمي المتفَّق عليه)
[null,null,["تاريخ التعديل الأخير: 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)."]]