Create and send draft emails
Stay organized with collections
Save and categorize content based on your preferences.
This document explains how to create, update, and send draft emails using the Gmail API.
Email 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
drafts resource is a
container that provides a stable ID because the underlying message IDs change
every time the message is replaced.
The messages resource
inside a draft has 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 message
with an updated ID is created with the
SENTsystem label. This message is returned in thedrafts.sendmethod response.
Create drafts
Your app can create drafts using the
drafts.create
method. To create a draft:
- Create a MIME message that complies with RFC 2822.
- Convert the message to a base64URL encoded string.
- Call the
drafts.createmethod, setting the value of themessages.rawfield to the encoded string.
The following code samples 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 */ publicclass CreateDraft{ /** * 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 client Gmailservice=newGmail.Builder(newNetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer) .setApplicationName("Gmail samples") .build(); // Create the email content StringmessageSubject="Test message"; StringbodyText="lorem ipsum."; // Encode as MIME message Propertiesprops=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 message ByteArrayOutputStreambuffer=newByteArrayOutputStream(); email.writeTo(buffer); byte[]rawMessageBytes=buffer.toByteArray(); StringencodedEmail=Base64.encodeBase64URLSafeString(rawMessageBytes); Messagemessage=newMessage(); message.setRaw(encodedEmail); try{ // Create the draft message Draftdraft=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 appropriately GoogleJsonErrorerror=e.getDetails(); if(error.getCode()==403){ System.err.println("Unable to create draft: "+e.getMessage()); }else{ throwe; } } returnnull; } }
Python
importbase64 fromemail.messageimport EmailMessage importgoogle.auth fromgoogleapiclient.discoveryimport build fromgoogleapiclient.errorsimport HttpError defgmail_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 client service = 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 message encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode() create_message = {"message": {"raw": encoded_message}} # pylint: disable=E1101 draft = ( service.users() .drafts() .create(userId="me", body=create_message) .execute() ) print(f'Draft id: {draft["id"]}\nDraft message: {draft["message"]}') except HttpError as error: print(f"An error occurred: {error}") draft = None return draft if __name__ == "__main__": gmail_create_draft()
cURL
curl--requestPOST\
'https://gmail.googleapis.com/gmail/v1/users/me/drafts'\
--header'Authorization: Bearer ACCESS_TOKEN" \
--header 'Accept:application/json' \
--header 'Content-Type:application/json' \
--data '{"message":{"raw":"MESSAGE"}}'
Replace the following:
- ACCESS_TOKEN: the access token that grants access to the API.
- MESSAGE: the RFC 2822 formatted MIME message, encoded as base64URL.
Update drafts
Similar to creating a draft, to update a draft you must supply a drafts
resource in the body of your request with the messages.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 the
drafts.get method
with the query parameter format=raw.
For more information, see the
drafts.update
method.
Send drafts
When sending a draft, you can send it as-is, or you can provide updates in the send request.
To update the draft when sending, supply a drafts resource in the request body
of the drafts.send
method. In the drafts resource, you must specify the draft
id of
the draft to be sent and set the messages.raw field to the new MIME message
encoded as a base64URL string.
For information on sending a Gmail message, see Send messages.