Guest User

Untitled

a guest
May 30th, 2018
524
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. require 'net/imap'
  2. require 'tmail'
  3.  
  4. class ImapChecker
  5. include Singleton
  6.  
  7. SERVER = 'secure.emailsrvr.com'
  8. USERNAME = 'A'
  9. PASSWORD = 'A'
  10. SEARCH_CRITERIA = %w{ TO offset }
  11.  
  12. attr_accessor :exiting
  13.  
  14. def say(message)
  15. STDERR.puts message
  16. end
  17.  
  18. # inspired by Delayed::Worker
  19. def start
  20. say "Starting imap checker"
  21. trap('TERM') { say 'Exiting...'; ImapChecker.instance.exiting = true }
  22. trap('INT') { say 'Exiting...'; ImapChecker.instance.exiting = true }
  23. loop do
  24. counter = nil
  25. realtime = Benchmark.realtime do
  26. counter = scan
  27. end
  28. if counter.nonzero?
  29. say "#{counter} emails scanned at %.4f e/s" % [counter / realtime]
  30. end
  31. break if exiting
  32. sleep 10
  33. end
  34. ensure
  35. close_connection
  36. self.exiting = false
  37. end
  38.  
  39. def connection
  40. return @_connection if @_connection.is_a?(Net::IMAP)
  41. @_connection = Net::IMAP.new SERVER, '993', true
  42. @_connection.login USERNAME, PASSWORD
  43. @_connection.examine 'INBOX'
  44. @_connection
  45. end
  46.  
  47. def close_connection
  48. connection.logout
  49. connection.disconnect
  50. @_connection = nil
  51. end
  52.  
  53. def scan
  54. counter = 0
  55. connection.check
  56. uids = connection.uid_search SEARCH_CRITERIA
  57. connection.uid_fetch(uids, %w{ ENVELOPE BODY[] }).each do |message|
  58. envelope = message.attr['ENVELOPE']
  59. from = "#{envelope.from[0].mailbox}@#{envelope.from[0].host}"
  60. body = TMail::Mail.parse(message.attr['BODY[]']).body
  61. incoming_message = IncomingMessage.new from, body
  62. counter += 1 if incoming_message.newly_processed?
  63. end if uids.length > 0
  64. counter
  65. end
  66. end
Add Comment
Please, Sign In to add comment