From: Masatoshi SEKI Date: 2000-02-29T00:09:02+09:00 Subject: [ruby-list:21087] tiny fetchmail 咳といいます。 今日の午前中、急に必要になって 定期的にPOPしてMain/inboxに保存する fetchmailもどきを書きました。 # が、午後になったらすぐ不要になってしまいました。 せっかくなので投稿します。 お目汚しにどうぞ。 % ruby script.rb とすると一分おきにPOPしてinboxに保存します。 引数検査の部分をちゃんと作らないと実用にならないかも。 #!/usr/local/bin/ruby require 'net/pop' class FetchMailError 0 count -= 1 retry else nil end end end def each @pop.each do |mail| yield mail end end def passwd system "stty -echo" print "Password: " pw = gets.chomp system "stty echo" puts pw end end class Inbox def initialize(path='~/Mail/inbox') @path = File.expand_path(path) end def tail f = -1 Dir.foreach(@path) do |name| if name =~ /^\d+$/ n = name.to_i f = (f > n) ? f : n end end f end def temp(count = 3) begin temppath = @path + "/poptemp#{$$}-#{count}" if File.exist?(temppath) count -= 1 if count > 0 retry else nil end end f = File.open(temppath, "w") [temppath, f] end end def summary(str) if str =~ /\nFrom: (.*?)\n/ puts "#{Time.now} From: #{$1}" end end def regist(mail, count = 8) str = mail.all() str.gsub!(/\r/, '') summary(str) temppath, f = temp() f.write(str) f.close() num = tail() + 1 begin new_name = @path + "/#{num}" File.link(temppath, new_name) File.unlink(temppath) mail.delete! rescue Errno::EEXIST if count > 0 num += 1 count -= 1 retry else nil end end end end class FetchMail def initialize(pop, inbox, interval=5) @pop = pop @inbox = inbox @interval= interval * 60 end def fetch @pop.reopen @pop.each do |mail| @inbox.regist(mail) end @pop.close end def mainloop loop do fetch sleep(@interval) end end end if __FILE__ == $0 inbox = Inbox.new pop = POPServer.new(ARGV.shift, ARGV.shift) begin fm = FetchMail.new(pop, inbox, 1) fm.mainloop ensure pop.close if pop end end