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.