在Ruby上使用Gmail API创建电子邮件草稿(google-api-ruby-client 0.9)

时间:2016-08-14 04:52:16

标签: ruby google-api gmail gmail-api google-api-ruby-client

我目前正在尝试使用Ruby和Google API for Ruby,但我无法访问我的Gmail帐户并使用服务帐户创建草稿(通过create_user_draft)。我已使用API​​成功验证了我的服务帐户(正在生成访问令牌)。

我可以将其用于Google::Apis::DriveV2::DriveService::list_files,但不能用于GmailV1方法。

我使用此代码来授权服务帐户和范围https://www.googleapis.com/auth/gmail.compose

授权

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

它使用以下格式生成访问令牌: {"access_token"=>"ya29.access_token_codes_here", "token_type"=>"Bearer", "expires_in"=>3600}

草稿创建者代码段

@@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

使用上述代码抛出failedPrecondition: Bad Request (Google::Apis::ClientError),但当我添加options: {authorization: @accessToken }作为create_user_draft的第三个参数时,异常变为Unauthorized (Google::Apis::AuthorizationError)

你能帮我走正确的道路吗?我发现在Google API网站和源代码本身上的API文档乏善可陈。

更新
read here为了使服务帐户能够使用Gmail API,需要付费的Google Apps帐户(正常的@ gmail.com帐户无法正常工作),因为在管理控制台上我们应该这样做必须为我们的服务帐户启用范围。

目前正在试用JWT Credentials登录。

0 个答案:

没有答案