簡體   English   中英

如何使用Ruby訪問Gmail API?

[英]How to access gmail api using ruby?

我正在嘗試使用該rubygmail指南來訪問gmail api,但每次嘗試運行該代碼時,都會遇到不同的錯誤,我正在使用此代碼:

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

我該如何解決,請幫幫我。

使用此寶石Gem gmail

Gem gmail-ruby-api

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM