There are two ways to send email using the Gmail API:
- You can send it directly using the
messages.send
method. - You can send it from a draft, using the
drafts.send
method.
Emails are sent as base64url encoded strings within the raw
property of a
message resource. The high-level
workflow to send an email is to:
- Create the email content in some convenient way and encode it as a base64url string.
- Create a new message resource and set its
raw
property to the base64url string you just created. - Call
messages.send
, or, if sending a draft,drafts.send
to 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 with RFC 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 MimeMessage
class 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 Message
object, and set the base64url encoded message string as the value of the
raw
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 Message
resource:
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 Message
resource.
Sending messages
Once you have created a message, you can send it by supplying it in the
request body of a call to
messages.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:
- The
Subject
headers match - The
References
andIn-Reply-To
headers follow the RFC 2822 standard.
For information on sending a message from a draft, see Creating Drafts.