popmail3.rb:
POPサーバからメールを取得し、SQLiteのDatabaseに保存するrubyスクリプト
メールボックスをDBテーブルにすれば、メールの削除とか振り分けとかが簡単にできそう。


# 取得したメールをSQLiteのDBに保存する。

require 'net/pop'
require 'mailparser'
require 'MBox'
require 'stringio'
require 'mailutil'

$KCODE = 'SJIS'
server = 'mail.xxx'
port = 110
user = 'xxx'
password = 'xxx'
pop = Net::POP3.new(server, port)
pop.start(user, password)

database = SQLite3::Database.new("mail.db")
inbox = MBox.new(database, "inbox")

if pop.mails.empty? then
puts 'no mail'
else
pop.each_mail {|mail|
# mail.unique_idをキーにDBに行があるか調べる。
unique_id = mail.unique_id
if inbox.has_row(unique_id) != 0
next
end

# なければ、DBに保存する。
content = mail.pop
StringIO.open(content, "r+b") {|f|
message = MailParser.parse_message f
from = Kconv::kconv(message[:from][0], Kconv::SJIS, Kconv::JIS)
to = Kconv::kconv(message[:to][0], Kconv::SJIS, Kconv::JIS)
date = message[:date].to_i
subject = Kconv::kconv(message[:subject], Kconv::SJIS, Kconv::JIS)

printf("%-s ", MailUtil::getDateStr(date))
printf("%-14s ", from[0..13])
#printf("%-14s ", to[0..13])
printf("%-36s ", subject[0..35])
printf("\n")

#p message[:body]
#parts = message[:parts]
inbox.insert(unique_id, from, to, date, subject, content)
}
}
end

内部で使っているmailutilはいまのところ、時間を文字列にするプロシージャだけ。

module MailUtil
H24SEC = 24 * 60 * 60

def getDateStr(tv_sec)
now = Time.now.tv_sec
if now - tv_sec < H24SEC * 30
return Time.at(tv_sec).strftime("%m/%d %H:%M")
else
return Time.at(tv_sec).strftime("%m/%d/%Y ")
end
end

module_function :getDateStr
end