Ruby1.9 は、mail でどうぞ -> Ruby1.9 でメール解析(変なヤバいもんログ内)
Tmailというライブラリを使うと、メールを解析して扱いやすくしてくれます。
Tmailのインストール
# gem install tmail |
パース方法
ファイルからパースする
メールがファイルであるならば、Fileクラスのインスタンスを渡してTMailクラスのインスタンスを作る。
receive1.rb
#! /usr/bin/ruby -w require 'rubygems' require 'tmail' file = File.open('mail.txt'){|f| f.read} email = TMail::Mail.load(file) p 'to: ', email.to p 'from', email.from |
TMail::Mail.load を使ってFileクラスのインスタンスを渡すとそれを解析してくれる。mail.txt で FromとToが以下のようになっていたとすると、それぞれが配列に入る。
From: [email protected]
To: [email protected]
$ ruby receive1.rb "to: " ["[email protected]"] "from: " ["[email protected]"] |
標準入力からパースする
receive2.rb
#! /usr/bin/ruby -w require 'rubygems' require 'tmail' email = TMail::Mail.parse(STDIN.read) p 'to: ', email.to p 'from', email.from |
$ cat mai.txt|ruby receive2.rb "to: " ["[email protected]"] "from: " ["[email protected]"] |
添付ファイルを取得する
tmailダウンロードするとサンプルがついているので、それにならう。
receive3.rb
#! /usr/bin/ruby require 'rubygems' require 'tmail' def main mail = TMail::Mail.parse(STDIN.read) mail.to # To: を取得 mail.from # From: を取得 idx = 1 # 複数の添付ファイルがあった場合のファイル名にしてる mail.parts.each do |m| m.base64_decode File.open("#{idx}.#{ext(m)}", 'w') {|f| f.write m.body } idx += 1 end end CTYPE_TO_EXT = { 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/png' => 'png', 'image/tiff' => 'tiff' } def ext( mail ) CTYPE_TO_EXT[mail.content_type] || 'txt' end main |
$ cat mai.txt|ruby receive3.rb |
これで、1.jpg, 2.png のようなファイル名で添付ファイル保存されるので、これで何かしたかったら分かるように保存しておけばOK。
メールサーバに来たメールを解析するとき
メールサーバにメールが届いたらそれをトリガーにして エイリアス作って渡してあげます。トリガーのひきかたは、省略。
/etc/aliases に以下のように記述して、 [email protected] に来たメールを引数で渡すようにします。
chihaya: "|/usr/bin/ruby /home/chihaya/receive3.rb"
あとは STDIN.read で標準入力を読んで処理すれば大丈夫。解析後のデータを使ってお好きなように。