Working with Drafts Stay organized with collections Save and categorize content based on your preferences.
Drafts represent unsent messages with theDRAFT system label applied.The message contained within the draft cannot be edited once created, but itcan be replaced. In this sense, thedraft resource is simply a containerthat provides a stable ID because the underlying message IDs change every timethe message is replaced.
Message resources inside a drafthave similar behavior to other messages except for the following differences:
- Draft messages cannot have any label other than the
DRAFTsystem label. - When the draft is sent, the draft is automatically deleted and a new messagewith an updated ID is created with the
SENTsystem label. This message isreturned in thedrafts.sendresponse.
Contents
Creating draft messages
Your application can create drafts using thedrafts.create method. Thegeneral process is to:
- Create a MIME message that complies withRFC 2822.
- Convert the message to a base64url encoded string.
- Create a draft, setting thevalue of the
drafts.message.rawfield to the encoded string.
The following code examples demonstrate the process.
Java
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;}}
Python
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 aDraftresource in the body of your request with thedraft.message.raw fieldset to a base64url encoded string containing the MIME message. Becausemessages cannot be updated, the message contained in the draft is destroyedand replaced by the new MIME message supplied in the update request.
You can retrieve the current MIME message contained in the draft by callingdrafts.get with the parameterformat=raw.
For more information, seedrafts.update.
Sending drafts
When sending a draft, you can choose to send the message as-is or as with anupdated message. If you are updating the draft content with a new message,supply aDraft resource in the body of thedrafts.send request; set thedraft.id of the draft to be sent; and set thedraft.message.raw field to thenew MIME message encoded as a base64url encoded string. For moreinformation, seedrafts.send.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-11 UTC.