2017年1月21日土曜日

簡単にGmailの下書きを作れるGemを作ったお

GmailApiJp
https://github.com/kenta-s/gmail_api_jp

GmailのAPIを使っていろいろできるんだけども、
少し難しかったり日本語を使う場合は特別な処理が必要だったりして大変なので、
簡単に扱えるGemを作りました。

いまのところ下書きを作成するだけですが、必要に迫られたら拡張していく予定です。

使い方

まずはアプリケーションを認証しないといけないので、こちらを参考にclient_secret.jsonを用意してください
https://developers.google.com/gmail/api/quickstart/ruby

そしてgem install
$ gem install gmail_api_jp

gmail_draft.ymlというファイルを配置(通常はアプリケーションのルートディレクトリ)して、
中身はこんな感じ
application_name: 認証時に入力したアプリケーション名 
client_secrets_path: "/Path/to/your/client_secret.json"


下書きにしたいメールのテキストを変数なりに準備して
text =<<TEXT
To: foo@example.com
Cc: bar@example.com, baz@example.com
Subject: こんにちは

こんにちは
ご機嫌いかがですか
TEXT

draft = GmailApiJp::Draft.new(text)
draft.create_draft
で、Gmailにログインすると下書きができているはず。

※初回のGmailApiJp::Draft.new時はアプリケーションを認証するために対話モードでトークンの入力を求められます。
指示に従って認証してください。

Issue, PRまってます

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化したのでこのレポジトリは削除しました