要在Ruby on Rails应用中使用Gmail API检查用户电子邮件中的某些关键字,你需要完成以下步骤:
Gemfile
中添加以下gem:gem 'google-api-client', '~> 0.53.0' gem 'googleauth', '~> 0.14.0'
然后运行bundle install
。
class GmailController < ApplicationController require 'google/apis/gmail_v1' require 'googleauth' require 'googleauth/stores/file_token_store' require 'fileutils' OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'.freeze APPLICATION_NAME = 'Gmail API Ruby Quickstart'.freeze CREDENTIALS_PATH = 'path/to/credentials.json'.freeze TOKEN_PATH = 'token.yaml'.freeze SCOPE = Google::Apis::GmailV1::AUTH_GMAIL_READONLY def authorize client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH) token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH) authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store) user_id = 'default' 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:\n" + url code = gets credentials = authorizer.get_and_store_credentials_from_code( user_id: user_id, code: code, base_url: OOB_URI ) end credentials end def list_messages service = Google::Apis::GmailV1::GmailService.new service.client_options.application_name = APPLICATION_NAME service.authorization = authorize user_id = 'me' result = service.list_user_messages(user_id) puts 'Messages:' puts 'No messages found' if result.messages.empty? result.messages.each { |message| puts "- #{message.id}" } end def search_emails(keyword) service = Google::Apis::GmailV1::GmailService.new service.client_options.application_name = APPLICATION_NAME service.authorization = authorize user_id = 'me' query = "subject:#{keyword}" result = service.list_user_messages(user_id, q: query) if result.messages.empty? puts 'No messages found' else result.messages.each do |message| msg = service.get_user_message(user_id, message.id) puts "Message snippet: #{msg.snippet}" end end end end
config/routes.rb
中添加路由:Rails.application.routes.draw do get 'gmail/authorize', to: 'gmail#authorize' get 'gmail/list_messages', to: 'gmail#list_messages' get 'gmail/search_emails', to: 'gmail#search_emails' end 创建一个简单的视图来触发这些操作。
领取专属 10元无门槛券
手把手带您无忧上云