如何使用ruby访问gmail api?

时间:2016-08-04 20:03:51

标签: ruby-on-rails ruby-on-rails-4 gmail-api

我正在尝试访问gmail api,因为我正在使用此rubygmail指南,但每次我尝试运行代码时,我都会遇到不同的错误,我正在使用此代码:

 require 'google/apis/gmail_v1'
  require 'googleauth'
  require 'googleauth/stores/file_token_store'

  require 'fileutils'

  OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
  APPLICATION_NAME = 'Gmail API Ruby Quickstart'
  CLIENT_SECRETS_PATH = 'client_secret.json'
  CREDENTIALS_PATH = File.join(Dir.home, '.credentials',
                               "gmail-ruby-quickstart.yaml")
  SCOPE = Google::Apis::GmailV1::AUTH_GMAIL_READONLY

  ##
  # Ensure valid credentials, either by restoring from the saved credentials
  # files or intitiating an OAuth2 authorization. If authorization is required,
  # the user's default browser will be launched to approve the request.
  #
  # @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
  def authorize
    FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))

    client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
    token_store = Google::Auth::Stores::FileTokenStore.new(:file => 'gmail-ruby-quickstart.yaml')
    authorizer = Google::Auth::UserAuthorizer.new(
      client_id, SCOPE, token_store)
    user_id = 'me'
     credentials = authorizer.get_credentials(user_id)
    if credentials.nil?
      url = authorizer.get_authorization_url(
        base_url: OOB_URI)
      puts "Open the following URL in the browser and enter the " +
           "resulting code after authorization"
      puts url
      code = gets
      credentials = authorizer.get_and_store_credentials_from_code(
        user_id: user_id, code: code, base_url: OOB_URI)
    end
    credentials
  end

  # Initialize the API
  service = Google::Apis::GmailV1::GmailService.new
  service.client_options.application_name = APPLICATION_NAME
  service.authorization = authorize

  # Show the user's labels
  user_id = 'me'
  result = service.list_user_labels(user_id)

  puts "Labels:"
  puts "No labels found" if result.labels.empty?
  result.labels.each { |label| puts "- #{label.name}" }

当我运行ruby代码时,我收到此错误:

       nilay@nilay:~/gmail$ ruby quickstart.rb
  /home/nilay/.rbenv/versions/2.3.1/lib/ruby/2.3.0/pstore.rb:414:in `load_data': PStore file seems to be corrupted. (PStore::Error)
    from /home/nilay/.rbenv/versions/2.3.1/lib/ruby/2.3.0/pstore.rb:328:in `transaction'
    from /home/nilay/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/googleauth-0.5.1/lib/googleauth/stores/file_token_store.rb:49:in `load'
    from /home/nilay/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/googleauth-0.5.1/lib/googleauth/user_authorizer.rb:130:in `get_credentials'
    from quickstart.rb:28:in `authorize'
    from quickstart.rb:45:in `<main>'

我该如何解决这个问题,请帮助我。

1 个答案:

答案 0 :(得分:0)

使用这个宝石 Gem gmail

Gem gmail-ruby-api