かまたま日記3

プログラミングメイン、たまに日常

GmailをAPI経由で取得する

GmailAPI経由で未読のメールを1件検索して既読にするサンプル。OAuthのトークンがない場合はコンソールに出てくるURLをブラウザで開いて認証後に出てくるコードを入力する。

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

Gmail = Google::Apis::GmailV1
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'

def credentials(email)
  @credentials ||= begin
    client_id = Google::Auth::ClientId.new(
      'xxxxx.apps.googleusercontent.com',
      'xxxxx'
    )
    token_store = Google::Auth::Stores::FileTokenStore.new(file: "#{ENV['HOME']}/google_credentials.yaml")
    authorizer = Google::Auth::UserAuthorizer.new(client_id, Gmail::AUTH_SCOPE, token_store)
    user_id = email
    credentials = authorizer.get_credentials(user_id)
    if credentials.nil?
      url = authorizer.get_authorization_url(base_url: OOB_URI)
      puts "Open the following URL in your browser and authorize the application."
      puts url
      puts "Enter the authorization code:"
      code = gets
      credentials = authorizer.get_and_store_credentials_from_code(
        user_id: user_id, code: code, base_url: OOB_URI
      )
    end
    credentials
  end
end

email = 'foo@gmail.com'
gmail = Gmail::GmailService.new
gmail.authorization = credentials(email)

result = gmail.list_user_messages(email, max_results: 1, q: 'label:inbox label:unread')
result.messages.each do |m|
  puts m.id
  puts gmail.get_user_message(email, m.id).snippet
  r = Gmail::ModifyMessageRequest.new
  r.remove_label_ids = ["UNREAD"]
  result = gmail.modify_message(email, m.id, r)
end