Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'net/imap'
- require 'tmail'
- class ImapChecker
- include Singleton
- SERVER = 'secure.emailsrvr.com'
- USERNAME = 'A'
- PASSWORD = 'A'
- SEARCH_CRITERIA = %w{ TO offset }
- attr_accessor :exiting
- def say(message)
- STDERR.puts message
- end
- # inspired by Delayed::Worker
- def start
- say "Starting imap checker"
- trap('TERM') { say 'Exiting...'; ImapChecker.instance.exiting = true }
- trap('INT') { say 'Exiting...'; ImapChecker.instance.exiting = true }
- loop do
- counter = nil
- realtime = Benchmark.realtime do
- counter = scan
- end
- if counter.nonzero?
- say "#{counter} emails scanned at %.4f e/s" % [counter / realtime]
- end
- break if exiting
- sleep 10
- end
- ensure
- close_connection
- self.exiting = false
- end
- def connection
- return @_connection if @_connection.is_a?(Net::IMAP)
- @_connection = Net::IMAP.new SERVER, '993', true
- @_connection.login USERNAME, PASSWORD
- @_connection.examine 'INBOX'
- @_connection
- end
- def close_connection
- connection.logout
- connection.disconnect
- @_connection = nil
- end
- def scan
- counter = 0
- connection.check
- uids = connection.uid_search SEARCH_CRITERIA
- connection.uid_fetch(uids, %w{ ENVELOPE BODY[] }).each do |message|
- envelope = message.attr['ENVELOPE']
- from = "#{envelope.from[0].mailbox}@#{envelope.from[0].host}"
- body = TMail::Mail.parse(message.attr['BODY[]']).body
- incoming_message = IncomingMessage.new from, body
- counter += 1 if incoming_message.newly_processed?
- end if uids.length > 0
- counter
- end
- end
Add Comment
Please, Sign In to add comment