0

I am currently trying out Ruby and the Google API for Ruby and I am having difficulties accessing my Gmail account and creating drafts with it (via create_user_draft) using a Service Account. I have successfully authenticated my Service Account with the API (Access Tokens are being generated).

I can use it with the Google::Apis::DriveV2::DriveService::list_files but not on GmailV1 methods.

I use this code to authorise the service account and the scope https://www.googleapis.com/auth/gmail.compose

Authorisation

def authorise
  @jsonKeyIo = self.loadCredentialsFile
  gAuthDefaultCreds = @@gAuthDefaultCreds
  serviceAccountCredentials = gAuthDefaultCreds.make_creds(
    {json_key_io:  @jsonKeyIo, scope: @scope})
  @service.authorization = serviceAccountCredentials
  @service.authorization.fetch_access_token!
end

It generates an access token with this format: {"access_token"=>"ya29.access_token_codes_here", "token_type"=>"Bearer", "expires_in"=>3600}

Draft creator snippet

@@gmail = Google::Apis::GmailV1
@@service = @@gmail::GmailService.new

def createDraft(draftTitle, draftMessage)
  draft = @@gmail::Draft.new
  draft.message = draftMessage
  @service.create_user_draft('my.email@gmail.com', draft)
end

It throws a failedPrecondition: Bad Request (Google::Apis::ClientError) with the above code but when I added options: {authorization: @accessToken } as a third parameter of create_user_draft, the exception becomes Unauthorized (Google::Apis::AuthorizationError).

Can you help me go to the right path? I find the API documentation, on the Google API sites and on the source code itself, lackluster.

UPDATE
I have read here that in order for Service Accounts to work on the Gmail API, a paid Google Apps account is required (normal @gmail.com accounts won't work) since on the Admin Console is where we should have to enable the scopes for our Service Accounts.

Currently trying out JWT Credentials login.

Community
  • 1
  • 1
neilbrysonmc
  • 11
  • 2
  • 4
  • Try to check this SO question [Creating draft via Google Gmail API](http://stackoverflow.com/questions/25493213/creating-draft-via-google-gmail-api) and [how to send message using Gmail API with Ruby Google API Client?](http://stackoverflow.com/questions/25396463/how-to-send-message-using-gmail-api-with-ruby-google-api-client) if it can help you. – KENdi Aug 16 '16 at 02:37
  • Any luck solving this issue? I have same `Google::Apis::ClientError: failedPrecondition: Bad Request` error and don't know how to deal with it. – Piotr Pawlik Mar 10 '17 at 11:47

0 Answers0