imap.rb 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
  2. require 'net/imap'
  3. class Channel::IMAP < Channel::EmailParser
  4. def fetch (channel, check_type = '', verify_string = '')
  5. ssl = true
  6. port = 993
  7. if channel[:options].key?(:ssl) && channel[:options][:ssl].to_s == 'false'
  8. ssl = false
  9. port = 143
  10. end
  11. Rails.logger.info "fetching imap (#{channel[:options][:host]}/#{channel[:options][:user]} port=#{port},ssl=#{ssl})"
  12. # on check, reduce open_timeout to have faster probing
  13. timeout = 12
  14. if check_type == 'check'
  15. timeout = 6
  16. end
  17. Timeout.timeout(timeout) do
  18. @imap = Net::IMAP.new( channel[:options][:host], port, ssl, nil, false )
  19. end
  20. # try LOGIN, if not - try plain
  21. begin
  22. @imap.authenticate( 'LOGIN', channel[:options][:user], channel[:options][:password] )
  23. rescue => e
  24. if e.to_s !~ /(unsupported\s(authenticate|authentication)\smechanism|not\ssupported)/i
  25. raise e
  26. end
  27. @imap.login( channel[:options][:user], channel[:options][:password] )
  28. end
  29. if !channel[:options][:folder] || channel[:options][:folder].empty?
  30. @imap.select('INBOX')
  31. else
  32. @imap.select( channel[:options][:folder] )
  33. end
  34. if check_type == 'check'
  35. Rails.logger.info 'check only mode, fetch no emails'
  36. disconnect
  37. return
  38. elsif check_type == 'verify'
  39. Rails.logger.info "verify mode, fetch no emails #{verify_string}"
  40. end
  41. message_ids = @imap.search(['ALL'])
  42. count_all = message_ids.count
  43. count = 0
  44. # reverse message order to increase performance
  45. if check_type == 'verify'
  46. message_ids.reverse!
  47. end
  48. message_ids.each do |message_id|
  49. count += 1
  50. Rails.logger.info " - message #{count}/#{count_all}"
  51. #Rails.logger.info msg.to_s
  52. # check for verify message
  53. if check_type == 'verify'
  54. subject = @imap.fetch(message_id, 'ENVELOPE')[0].attr['ENVELOPE'].subject
  55. if subject && subject =~ /#{verify_string}/
  56. Rails.logger.info " - verify email #{verify_string} found"
  57. @imap.store(message_id, '+FLAGS', [:Deleted])
  58. @imap.expunge()
  59. disconnect
  60. return 'verify ok'
  61. end
  62. else
  63. # delete email from server after article was created
  64. msg = @imap.fetch(message_id, 'RFC822')[0].attr['RFC822']
  65. if process(channel, msg)
  66. @imap.store(message_id, '+FLAGS', [:Deleted])
  67. end
  68. end
  69. end
  70. @imap.expunge()
  71. disconnect
  72. if count == 0
  73. Rails.logger.info ' - no message'
  74. end
  75. Rails.logger.info 'done'
  76. end
  77. def disconnect
  78. return if !@imap
  79. @imap.disconnect()
  80. end
  81. end