1.21 jigowatts

Great Scott!

Ruby RSSをパースしてGmail送信してみる

概要

新聞取ってますか?ニュース見てますか?私はあまり見てません( ˘ω˘)
社会人としてこれじゃまずいですよね。はい、RSS配信されているニュースを無駄にRubyGmail配信します。メールだと強制的に見るんですよ。

環境

Ruby: 2.3.1

RSSをパースする

パースするRSSNHKの主要ニュースにしました。RSS2.0です。ん?受信料?ちゃんと払ってますよ。
NHKオンライン|RSSについて

ライブラリは標準ライブラリのRSSを使ってみました。
まずは動かしてみるとこから。

require 'rss'

# NHK(RSS 2.0)
url = "http://www3.nhk.or.jp/rss/news/cat0.xml"
rss = RSS::Parser.parse(url)

rss.items.each do |item|
  puts "Title: #{item.title}"
  puts "Link: #{item.link}"
  puts "Description: #{item.description}"
  puts "-"*50
end

Gmailを送信する

ライブラリのインストール

$ gem install gmail

Gmailの2段階認証プロセスを有効にして、アプリパスワードを作っておきましょう。
アプリ パスワードでログイン - Gmail ヘルプ

パスワードはこのアプリパスワードを設定します。

require 'gmail'

id = "<your_mail_address@gmail.com>"
pass = "<your password>"

gmail = Gmail.connect(id,pass)
gmail.deliver do
  to "send_to@gmail.com"
  subject "subject"
  html_part do
    content_type 'text/html; charset=UTF-8'
    body "contents"
  end
end

gmail.logout

コード一式

なんとなく動作するようになったので組み立てます。ファイル分けすぎたかな。Rubyっぽい書き方ができているのかまだわかりませn

■content.rb

class Content
  def initialize(title,link,description)
    @title = title
    @link = link
    @description = description
  end
  
  attr_accessor :title, :link, :description
end

■news.rb
パースしたやつをContentクラスに詰め込んで、配列にさらに突っ込んで。Hash?Structがいい?

require 'rss'

require './content'

class News
  def get_contents
    @news = []

    # NHK(RSS 2.0)
    url = "http://www3.nhk.or.jp/rss/news/cat0.xml"
    rss = RSS::Parser.parse(url)

    rss.items.each do |item|
      content = Content.new(
        item.title,
        item.link,
        item.description
        )
      @news.push(content)
    end

    format
  end

  private  
  def format
    str = "<h1>#{DateTime.now.strftime("%Y-%m-%d %H:%M:%S")}</h1>"

    @news.each do |content|
      str << "<a href='#{content.link}'>#{content.title}</a>"
      str << "<p>#{content.description}</p>"
    end

    return str
  end
end

■mailer.rb

require 'gmail'

class Mailer
  def initialize(id,pass)
    @id = id
    @pass = pass
  end

  def send(send_to,subject,contents)
    gmail = Gmail.connect(@id,@pass)
    gmail.deliver do
      to send_to
      subject subject
      html_part do
        content_type 'text/html; charset=UTF-8'
        body contents
      end
    end

    gmail.logout
  end
end

■main.rb

require './news'
require './mailer'
require './config'

# コンテンツ取得
news = News.new
contents = news.get_contents

# メール送信
mailer = Mailer.new(ID,PASS)

ADDRESS_BOOK.each do |address|
  mailer.send(address,SUBJECT,contents)
end

■config.rb
宛先は配列にして複数人に送れるようにしたけど、そんな送る相手もいなかった!YAGNI!!うるせーっ(´;ω;`)

# config
ADDRESS_BOOK = ["send_to@gmail.com"]
SUBJECT = "Today's News"

# secret
ID = "<your_mail_address@gmail.com>"
PASS = "<your password>"

実行結果

$ ruby main.rb

送ったメールをiPhoneで見てみましょう。

f:id:sh_yoshida:20161007183724p:plain

定期的にメールに送っておけば最低限の情報はチェックできるはず。これで社会人として道の真ん中歩けますね。

(´・ω・) RSSリーダー.. (・ω・`)