How to set email recipients when creating Gmail drafts via API

I’m working with the Gmail API using Ruby and I can successfully create draft messages. However, I’m having trouble adding recipients to these drafts. The draft gets created fine but no recipients are included.

I looked at existing drafts through the Google API explorer and tried to copy their structure. Here’s what I’m attempting:

response = gmail_client.execute(
  :api_method => gmail_service.users.drafts.create,
  :parameters => {
    'userId' => "me"
  },
  :body_object => {
    'message' => {
      'raw' => Base64.urlsafe_encode64('Sample draft content'),
      'payload' => {
        'headers' => [
          {
            'name' => "To",
            'value' => "Jane Doe <[email protected]>"
          }
        ]
      }
    }
  }
)

The draft appears in Gmail but without any recipients set. What’s the correct way to include recipient information when creating drafts through the Gmail API?

You’re mixing raw and structured message formats, which won’t work. When you use the raw parameter, you need the entire RFC 2822 formatted message as a string with headers included. You can’t use both raw and payload together.

Here’s how to build the full message string:

message_content = [
  "To: [email protected]",
  "Subject: Your Subject Here",
  "",
  "Sample draft content"
].join("\r\n")

response = gmail_client.execute(
  :api_method => gmail_service.users.drafts.create,
  :parameters => {
    'userId' => "me"
  },
  :body_object => {
    'message' => {
      'raw' => Base64.urlsafe_encode64(message_content)
    }
  }
)

Or just ditch the raw parameter and stick with the payload structure using proper headers. I’ve had better luck with the raw approach for drafts that need recipients.

yeah, this is a common gmail api gotcha. you’re mixing raw + payload like others mentioned. i just stick with the raw approach since it’s simpler - just don’t forget the proper line breaks (\r\n) between headers and body or gmail can’t parse it right.

You can’t mix raw and payload parameters in the same request. When you use raw, Gmail requires a complete RFC 2822 message string that includes all headers in-line, rather than using separate payload objects. I faced a similar issue previously and found two solutions that work. The first option is to build your entire message as a string before encoding it. The second option is to discard the raw parameter and only utilize the payload structure. While the payload approach needs a proper setup for message parts, it allows for greater control over complex messages. Both methods work effectively as long as the formats are not mixed.