#!/usr/bin/ruby -Ke if ARGV.size < 1 then puts "Usage #{__FILE__} target_dir" exit end require 'tmail' require 'nkf' require 'jcode' target_dir = ARGV.shift.gsub(/\/$/, '') puts "Target Directory : #{target_dir}" mails = {} Dir::foreach(target_dir){|file| file_name = "#{target_dir}/#{file}" if file_name !~ /\.eml$/ then next end begin mails[file_name] = TMail::Mail::load(file_name) rescue p $! p $@ p file_name end } def check(str) candidates = [] str.scan(/\d{5,}/){|s| candidates << s } str.scan(/[£°-£¹]{5,}/){|s| candidates << s.tr("£°-£¹","0-9") } candidates.each{|item| if item !~ /20070/ then return item end } return nil end $sorted_mails = {} def add_sorted(num, file_mail) unless $sorted_mails.include?(num) then $sorted_mails[num] = [] end $sorted_mails[num] << file_mail end mails.each{|file, mail| file_mail = [file, mail] if mail.subject && (num = check(NKF::nkf('-e', mail.subject))) then add_sorted(num, file_mail) next end if mail.multipart? then mail.parts.each{|part| if part.content_type =~ /text/ && part.disposition !~ /(?:attachment|inline)/ then #puts part.disposition if part.body && (num = check(NKF::nkf('-e', part.body))) then add_sorted(num, file_mail) next end end } else if mail.body && (num = check(NKF::nkf('-e', mail.body))) then add_sorted(num, file_mail) end end } p $sorted_mails SORTED_DIR = './sorted' unless FileTest::exist?(SORTED_DIR) then Dir::mkdir(SORTED_DIR) end $sorted_mails.each{|num, file_mails| dir_name = "#{SORTED_DIR}/#{num}" unless FileTest::exist?(dir_name) then Dir::mkdir(dir_name) end file_mails.each{|file_mail| file, mail = file_mail command = "mv '#{file}' #{dir_name}" begin system(command) rescue p $! p $@ p command end } }