Sending Email Stay organized with collections Save and categorize content based on your preferences.
There are two ways to send email using the Gmail API:
- You can send it directly using the
messages.sendmethod. - You can send it from a draft, using the
drafts.sendmethod.
Emails are sent as base64url encoded strings within theraw property of amessage resource. The high-levelworkflow to send an email is to:
- Create the email content in some convenient way and encode it as abase64url string.
- Create a new message resource and set its
rawproperty to the base64urlstring you just created. - Call
messages.send, or, if sending a draft,drafts.sendto send the message.
The details of this workflow can vary depending on your choice of clientlibrary and programming language.
Creating messages
The Gmail API requires MIME email messages compliant withRFC 2822 andencoded as base64url strings. Many programming languages havelibraries or utilities that simplify the process of creating and encoding MIMEmessages. The following code examples demonstrate how to create a MIME messageusing the Google APIs client libraries for various languages.
Java
Creating an email message can be greatly simplified with theMimeMessageclass in thejavax.mail.internet package. The following example shows howto create the email message, including the headers:
importjava.util.Properties;importjavax.mail.MessagingException;importjavax.mail.Session;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeMessage;/* Class to demonstrate the use of Gmail Create Email API */publicclassCreateEmail{/** * Create a MimeMessage using the parameters provided. * * @param toEmailAddress email address of the receiver * @param fromEmailAddress email address of the sender, the mailbox account * @param subject subject of the email * @param bodyText body text of the email * @return the MimeMessage to be used to send email * @throws MessagingException - if a wrongly formatted address is encountered. */publicstaticMimeMessagecreateEmail(StringtoEmailAddress,StringfromEmailAddress,Stringsubject,StringbodyText)throwsMessagingException{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(subject);email.setText(bodyText);returnemail;}}
The next step is to encode theMimeMessage, instantiate aMessageobject, and set the base64url encoded message string as the value of theraw property.
importcom.google.api.services.gmail.model.Message;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjavax.mail.MessagingException;importjavax.mail.internet.MimeMessage;importorg.apache.commons.codec.binary.Base64;/* Class to demonstrate the use of Gmail Create Message API */publicclassCreateMessage{/** * Create a message from an email. * * @param emailContent Email to be set to raw of message * @return a message containing a base64url encoded email * @throws IOException - if service account credentials file not found. * @throws MessagingException - if a wrongly formatted address is encountered. */publicstaticMessagecreateMessageWithEmail(MimeMessageemailContent)throwsMessagingException,IOException{ByteArrayOutputStreambuffer=newByteArrayOutputStream();emailContent.writeTo(buffer);byte[]bytes=buffer.toByteArray();StringencodedEmail=Base64.encodeBase64URLSafeString(bytes);Messagemessage=newMessage();message.setRaw(encodedEmail);returnmessage;}}
Python
The following code sample demonstrates creating a MIME message, encoding toa base64url string, and assigning it to theraw field of theMessageresource:
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()
Creating messages with attachments
Creating a message with an attachment is like creating any other message,but the process of uploading the file as a multi-part MIMEmessage depends on the programming language. The following codeexamples demonstrate possible ways of creating a multi-part MIME message withan attachment.
Java
The following example shows how to create a multi-part MIME message, theencoding and assignment steps are the same as above.
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.File;importjava.io.IOException;importjava.util.Properties;importjavax.activation.DataHandler;importjavax.activation.DataSource;importjavax.activation.FileDataSource;importjavax.mail.MessagingException;importjavax.mail.Multipart;importjavax.mail.Session;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeBodyPart;importjavax.mail.internet.MimeMessage;importjavax.mail.internet.MimeMultipart;importorg.apache.commons.codec.binary.Base64;/* Class to demonstrate the use of Gmail Create Draft with attachment API */publicclassCreateDraftWithAttachment{/** * Create a draft email with attachment. * * @param fromEmailAddress - Email address to appear in the from: header. * @param toEmailAddress - Email address of the recipient. * @param file - Path to the file to be attached. * @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. */publicstaticDraftcreateDraftMessageWithAttachment(StringfromEmailAddress,StringtoEmailAddress,Filefile)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);MimeBodyPartmimeBodyPart=newMimeBodyPart();mimeBodyPart.setContent(bodyText,"text/plain");Multipartmultipart=newMimeMultipart();multipart.addBodyPart(mimeBodyPart);mimeBodyPart=newMimeBodyPart();DataSourcesource=newFileDataSource(file);mimeBodyPart.setDataHandler(newDataHandler(source));mimeBodyPart.setFileName(file.getName());multipart.addBodyPart(mimeBodyPart);email.setContent(multipart);// 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.getDetails());}else{throwe;}}returnnull;}}
Python
Similar to the previous example, this example also handles encoding themessage to base64url and assigning it to theraw field of theMessageresource.
importbase64importmimetypesimportosfromemail.messageimportEmailMessagefromemail.mime.audioimportMIMEAudiofromemail.mime.baseimportMIMEBasefromemail.mime.imageimportMIMEImagefromemail.mime.textimportMIMETextimportgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordefgmail_create_draft_with_attachment():"""Create and insert a draft email with attachment. 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)mime_message=EmailMessage()# headersmime_message["To"]="gduser1@workspacesamples.dev"mime_message["From"]="gduser2@workspacesamples.dev"mime_message["Subject"]="sample with attachment"# textmime_message.set_content("Hi, this is automated mail with attachment.Please do not reply.")# attachmentattachment_filename="photo.jpg"# guessing the MIME typetype_subtype,_=mimetypes.guess_type(attachment_filename)maintype,subtype=type_subtype.split("/")withopen(attachment_filename,"rb")asfp:attachment_data=fp.read()mime_message.add_attachment(attachment_data,maintype,subtype)encoded_message=base64.urlsafe_b64encode(mime_message.as_bytes()).decode()create_draft_request_body={"message":{"raw":encoded_message}}# pylint: disable=E1101draft=(service.users().drafts().create(userId="me",body=create_draft_request_body).execute())print(f'Draft id:{draft["id"]}\nDraft message:{draft["message"]}')exceptHttpErroraserror:print(f"An error occurred:{error}")draft=Nonereturndraftdefbuild_file_part(file):"""Creates a MIME part for a file. Args: file: The path to the file to be attached. Returns: A MIME part that can be attached to a message. """content_type,encoding=mimetypes.guess_type(file)ifcontent_typeisNoneorencodingisnotNone:content_type="application/octet-stream"main_type,sub_type=content_type.split("/",1)ifmain_type=="text":withopen(file,"rb"):msg=MIMEText("r",_subtype=sub_type)elifmain_type=="image":withopen(file,"rb"):msg=MIMEImage("r",_subtype=sub_type)elifmain_type=="audio":withopen(file,"rb"):msg=MIMEAudio("r",_subtype=sub_type)else:withopen(file,"rb"):msg=MIMEBase(main_type,sub_type)msg.set_payload(file.read())filename=os.path.basename(file)msg.add_header("Content-Disposition","attachment",filename=filename)returnmsgif__name__=="__main__":gmail_create_draft_with_attachment()
Sending messages
Once you have created a message, you can send it by supplying it in therequest body of a call tomessages.send, as demonstratedin the following examples.
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.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 Send Message API */publicclassSendMessage{/** * Send an email from the user's mailbox to its recipient. * * @param fromEmailAddress - Email address to appear in the from: header * @param toEmailAddress - Email address of the recipient * @return the sent message, {@code null} otherwise. * @throws MessagingException - if a wrongly formatted address is encountered. * @throws IOException - if service account credentials file not found. */publicstaticMessagesendEmail(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_SEND);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 send messagemessage=service.users().messages().send("me",message).execute();System.out.println("Message id: "+message.getId());System.out.println(message.toPrettyString());returnmessage;}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelyGoogleJsonErrorerror=e.getDetails();if(error.getCode()==403){System.err.println("Unable to send message: "+e.getDetails());}else{throwe;}}returnnull;}}
Python
importbase64fromemail.messageimportEmailMessageimportgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordefgmail_send_message():"""Create and send an email message Print the returned message id Returns: Message object, including message id 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: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 messageencoded_message=base64.urlsafe_b64encode(message.as_bytes()).decode()create_message={"raw":encoded_message}# pylint: disable=E1101send_message=(service.users().messages().send(userId="me",body=create_message).execute())print(f'Message Id:{send_message["id"]}')exceptHttpErroraserror:print(f"An error occurred:{error}")send_message=Nonereturnsend_messageif__name__=="__main__":gmail_send_message()
If you're trying to send a reply and want the email to thread, make sure that:
- The
Subjectheaders match - The
ReferencesandIn-Reply-Toheaders follow theRFC 2822 standard.
For information on sending a message from a draft, seeCreating Drafts.
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.