Sending Email (original) (raw)

There are two ways to send email using the Gmail API:

Emails are sent as base64url encoded strings within the raw property of amessage resource. The high-level workflow to send an email is to:

  1. Create the email content in some convenient way and encode it as a base64url string.
  2. Create a new message resource and set its raw property to the base64url string you just created.
  3. 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 client library and programming language.

Creating messages

The Gmail API requires MIME email messages compliant withRFC 2822 and encoded as base64url strings. Many programming languages have libraries or utilities that simplify the process of creating and encoding MIME messages. The following code examples demonstrate how to create a MIME message using the Google APIs client libraries for various languages.

Java

Creating an email message can be greatly simplified with the MimeMessageclass in the javax.mail.internet package. The following example shows how to create the email message, including the headers:

The next step is to encode the MimeMessage, instantiate a Messageobject, and set the base64url encoded message string as the value of theraw property.

Python

The following code sample demonstrates creating a MIME message, encoding to a base64url string, and assigning it to the raw field of the Messageresource:

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 MIME message depends on the programming language. The following code examples demonstrate possible ways of creating a multi-part MIME message with an attachment.

Java

The following example shows how to create a multi-part MIME message, the encoding and assignment steps are the same as above.

Python

Similar to the previous example, this example also handles encoding the message to base64url and assigning it to the raw field of the Messageresource.

Sending messages

Once you have created a message, you can send it by supplying it in the request body of a call tomessages.send, as demonstrated in the following examples.

Java

Python

If you're trying to send a reply and want the email to thread, make sure that:

  1. The Subject headers match
  2. The References and In-Reply-To headers follow theRFC 2822 standard.

For information on sending a message from a draft, seeCreating Drafts.