Search code examples
rubygmail-apigoogle-api-client

Gmail API with service account


Under mygmailaccount@gmail.com in the API console I created a project and I am successfully using a service account for the Analytics API and Search Console API services. I've now enabled the Gmail V1 API and ran this code:

gmail_scopes = [
  "https://mail.google.com/",
  "https://www.googleapis.com/auth/gmail.compose",
  "https://www.googleapis.com/auth/gmail.readonly",
  "https://www.googleapis.com/auth/gmail.send",
  "https://www.googleapis.com/auth/gmail.readonly"
]
gmail = Google::Apis::GmailV1::GmailService.new
gmail.authorization = Google::Auth.get_application_default(gmail_scopes)

This is the same code (with different scopes of course) that I use to authorize the Analytics and Search Console API.

However I get BAD REQUEST Failed Precondition errors when I run this:

gmail.get_user_profile("mygmailaccount@gmail.com")

Some googling tells me that is because the API is trying to access the non-existent inbox for the serviceaccount email address and that in the initiatlization process I need to include mygmailaccount@gmail.com so that the API service will use that inbox.

How do I do that?

I've tried the following '...' always being the email address

gmail.authorization = Google::Auth.get_application_default(gmail_scopes, username: '...')
gmail.authorization = Google::Auth.get_application_default(gmail_scopes, {username: '...'})
gmail.authorization.username = '...'

Solution

  • Service accounts cannot access @gmail.com mailboxes. You need to use an OAuth2 UserAuthorizer. See the Gmail API Ruby Quickstart guide for an example.