2017年1月11日水曜日

RubyでGmail用APIを使って下書き(draft)を作成

タイトルの通りだが意外と情報が少なくて苦労した。

以下(公式)で公開されているものをベースにしているので、まずはこのURL内のサンプルコードが正しく動作することを確認することを推奨する。
認証の方法などもこちらに記載されている。 https://developers.google.com/gmail/api/quickstart/ruby

※使用しているgoogle-api-clientのバージョンは0.9.20
require 'google/apis/gmail_v1'
require 'googleauth'
require 'googleauth/stores/file_token_store'

require 'fileutils'

class GmailDraftJP
  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 = "https://mail.google.com/"

  def initialize(text)
    @service = Google::Apis::GmailV1::GmailService.new
    @service.client_options.application_name = APPLICATION_NAME
    @service.authorization = authorize
    @text = text.encode("ISO-2022-JP") # これがないと日本語が文字化け
  end

  def create_draft
    user_id = 'me'

    draft = Google::Apis::GmailV1::Draft.new
    message = Google::Apis::GmailV1::Message.new
    message.raw = @text
    draft.message = message

    @service.create_user_draft(user_id, draft)
    puts "====== Draft created ====="
  end

  private

  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: CREDENTIALS_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"
      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
end
ポイントはスコープの指定と、message.rawに渡す文字列、それから日本語に対応するためのエンコーディング。

こんな感じでcreate_draftメソッドを呼ぶとGmailで下書きが作成されているはず:
text =<<TEXT
To: foo@example.com
Cc: bar@example.com, baz@example.com
Subject: こんにちは

Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
TEXT

draft = GmailDraftJp.new(text)
draft.creat_draft
最初の一回目は認証を行う必要があるので指示に従ってtokenの入力などを行う。

ソースコードはGitHubにも公開しているのでどぞ
https://github.com/kenta-s/gmail-draft-jp
=> Gem化したのでこのレポジトリは削除しました

2 件のコメント:

  1. Wynn casino opens in Las Vegas - FilmfileEurope
    Wynn's first hotel casino https://deccasino.com/review/merit-casino/ in Las Vegas since opening its doors in 1996, https://deccasino.com/review/merit-casino/ Wynn aprcasino Las Vegas 토토 사이트 is the first hotel on the Strip to offer such a large selection of

    返信削除
  2. The dealer will flip over their own second card and either stand or take more 빅카지노 cards primarily based on the required guidelines of the game. A confident player may want to double down by making a further wager a lot as} the quantity of the unique guess. Doubling down could be done on any two-card combination, besides on blackjack and split Aces. A player taking this selection receives just one more card for the hand. If a player’s first two cards are of equal worth, the player has the choice of splitting them to create two separate arms.

    返信削除