imap.rb 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 = false
  6. port = 143
  7. if channel[:options][:ssl].to_s == 'true'
  8. ssl = true
  9. port = 993
  10. end
  11. puts "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 = 4
  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 Exception => e
  24. if e.to_s !~ /unsupported\s(authenticate|authentication)\smechanism/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. puts "check only mode, fetch no emails"
  36. disconnect
  37. return
  38. elsif check_type == 'verify'
  39. puts "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. puts " - message #{count.to_s}/#{count_all.to_s}"
  51. # puts 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. puts " - 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. puts " - no message"
  74. end
  75. puts "done"
  76. end
  77. def disconnect
  78. if @imap
  79. @imap.disconnect()
  80. end
  81. end
  82. end