Stay organized with collections
Save and categorize content based on your preferences.
Drafts represent unsent messages with the DRAFT system label applied.
The message contained within the draft cannot be edited once created, but it
can be replaced. In this sense, the
draft resource is simply a container
that provides a stable ID because the underlying message IDs change every time
the message is replaced.
Message resources inside a draft
have similar behavior to other messages except for the following differences:
Draft messages cannot have any label other than the DRAFT system label.
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
response.
Contents
Creating draft messages
Your application can create drafts using the
drafts.create method. The
general process is to:
Create a MIME message that complies with
RFC 2822.
Convert the message to a base64url encoded string.
Create a draft, setting the
value of the drafts.message.raw field to the encoded string.
The following code examples demonstrate the process.
importcom.google.api.client.googleapis.json.GoogleJsonError;importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.gmail.Gmail;importcom.google.api.services.gmail.GmailScopes;importcom.google.api.services.gmail.model.Draft;importcom.google.api.services.gmail.model.Message;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.util.Properties;importjavax.mail.MessagingException;importjavax.mail.Session;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeMessage;importorg.apache.commons.codec.binary.Base64;/* Class to demonstrate the use of Gmail Create Draft API */publicclassCreateDraft{/** * 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. */publicstaticDraftcreateDraftMessage(StringfromEmailAddress,StringtoEmailAddress)throwsMessagingException,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.*/GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(GmailScopes.GMAIL_COMPOSE);HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Create the gmail API clientGmailservice=newGmail.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Gmail samples").build();// Create the email contentStringmessageSubject="Test message";StringbodyText="lorem ipsum.";// Encode as MIME messagePropertiesprops=newProperties();Sessionsession=Session.getDefaultInstance(props,null);MimeMessageemail=newMimeMessage(session);email.setFrom(newInternetAddress(fromEmailAddress));email.addRecipient(javax.mail.Message.RecipientType.TO,newInternetAddress(toEmailAddress));email.setSubject(messageSubject);email.setText(bodyText);// Encode and wrap the MIME message into a gmail messageByteArrayOutputStreambuffer=newByteArrayOutputStream();email.writeTo(buffer);byte[]rawMessageBytes=buffer.toByteArray();StringencodedEmail=Base64.encodeBase64URLSafeString(rawMessageBytes);Messagemessage=newMessage();message.setRaw(encodedEmail);try{// Create the draft messageDraftdraft=newDraft();draft.setMessage(message);draft=service.users().drafts().create("me",draft).execute();System.out.println("Draft id: "+draft.getId());System.out.println(draft.toPrettyString());returndraft;}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelyGoogleJsonErrorerror=e.getDetails();if(error.getCode()==403){System.err.println("Unable to create draft: "+e.getMessage());}else{throwe;}}returnnull;}}
importbase64fromemail.messageimportEmailMessageimportgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordefgmail_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 clientservice=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 messageencoded_message=base64.urlsafe_b64encode(message.as_bytes()).decode()create_message={"message":{"raw":encoded_message}}# pylint: disable=E1101draft=(service.users().drafts().create(userId="me",body=create_message).execute())print(f'Draft id: {draft["id"]}\nDraft message: {draft["message"]}')exceptHttpErroraserror:print(f"An error occurred: {error}")draft=Nonereturndraftif__name__=="__main__":gmail_create_draft()
Updating drafts
Similarly to creating a draft, to update a draft you must supply a Draft
resource in the body of your request with the draft.message.raw field
set to a base64url encoded string containing the MIME message. Because
messages cannot be updated, the message contained in the draft is destroyed
and replaced by the new MIME message supplied in the update request.
You can retrieve the current MIME message contained in the draft by calling
drafts.get with the parameter
format=raw.
When sending a draft, you can choose to send the message as-is or as with an
updated message. If you are updating the draft content with a new message,
supply a Draft resource in the body of the
drafts.send request; set the
draft.id of the draft to be sent; and set the draft.message.raw field to the
new MIME message encoded as a base64url encoded string. For more
information, see drafts.send.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-04 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)."]]