require 'net/imap' class Message attr_reader :message_id, :subject, :sender_name, :sender_email, :date, :text def initialize( imap, message_id ) @imap, @message_id = imap, message_id envelope = @imap.fetch( @message_id, 'ENVELOPE' ).first.attr['ENVELOPE'] @subject = envelope['subject'] @sender_name = envelope['from'].first['name'] @sender_email = envelope['from'].first['mailbox'] + '@' + envelope['from'].first['host'] @text = plain_text_content_from_message( message_id ) end def plain_text_content_from_message( id ) text = @imap.fetch( id, 'BODY[1]' ).first.attr['BODY[1]'] text.gsub!(/\r\n/,"\n") text.gsub!(/\r/,"\n") text.gsub!(/=\n/,'') text.gsub!(/((?:=[0-9a-fA-F]{2})+)/n) { [$1.delete('=')].pack('H*') } text end end class Mail2WikiHelper DEFAULT_SETTINGS = { :server => 'imap.hermes.cam.ac.uk', :username => 'tamc2', :password => '', :mailbox => 'mcr notices', :check_frequency => 600, # Seconds :subject_regexp => /.*/, } def initialize( wiki, settings = {} ) @settings = DEFAULT_SETTINGS.merge( settings ) @wiki = wiki check_mailbox Thread.new do loop do sleep @settings[:check_frequency ] check_mailbox end end end private def check_mailbox login select_mailbox p "Checking for emails in #{@settings[:server]}" new_messages_for_wiki do |message_id| this_message = Message.new( @imap, message_id ) if this_message.subject =~ @settings[:subject_regexp] add_message_to_wiki( this_message ) mark_as_added( message_id ) end end logout end def add_message_to_wiki( message ) current_page = @wiki.page( message.subject ) if current_page.empty? text = "h1. #{message.subject}" else text = current_page.textile end text << "\n\n----\n\n" text << "#{message.date} from #{message.sender_name} #{message.sender_email}\n" text << message.text.gsub(/[\*-]{2,}/,'').gsub(/\n\s+/,"\n").gsub(/\n/,"\n\n") @wiki.revise(message.subject, text, message.sender_name ) end def login @imap = Net::IMAP.new(@settings[:server]) @imap.login( @settings[:username], @settings[:password] ) end def logout @imap.logout @imap.disconnect end def select_mailbox @imap.select @settings[:mailbox] end def new_messages_for_wiki @imap.search('UNKEYWORD PutInWiki').each { |id| yield id } end def mark_as_added( id ) # @imap.store( id, '+FLAGS', ['PutInWiki'] ) end end