RubyでGmailのAPIを叩く
GmailのAPIに関する情報がほとんどなかったので、ざくっと書き残しておきます。
前提条件
- access_tokenは取得している
- 公式クライアント(google/google-api-ruby-client · GitHub)を使う
サンプルコード
require "google/api_client" # メッセージの準備 message = Mail.new message.to = "example@example.com" message.subject = "こんにちは、Gmail! " # UTF-8使えます。 message.body = "Create draft via Gmail API. テストですよ、テスト。" # APIクライアントの準備 client = Google::APIClient.new(application_name: "app_name") client.authorization.access_token = access_token gmail = client.discovered_api("gmail") # APIを叩く res = client.execute( api_method: gmail.users.drafts.create, parameters: {"userId" => "me"}, body_object: { "message" => {"raw" => Base64.urlsafe_encode64(message.to_s)} } ) # あとはよしなに if res.status == 200 json = JSON.parse(res.body) # Do something else raise end
その他
- APIを叩くときのパラメータにRFC822準拠のメッセージを渡す必要があるので、Mailクラスを使っています。
- アクセストークンには適切なscopeが設定されている必要があります。
- サンプルアプリケーションがs-osa/auth_and_gmail · GitHubにあります。