imap.rb 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. @imap = Net::IMAP.new( channel[:options][:host], port, ssl, nil, false )
  13. # try LOGIN, if not - try plain
  14. begin
  15. @imap.authenticate( 'LOGIN', channel[:options][:user], channel[:options][:password] )
  16. rescue Exception => e
  17. if e.to_s !~ /unsupported\sauthentication\smechanism/i
  18. raise e
  19. end
  20. @imap.login( channel[:options][:user], channel[:options][:password] )
  21. end
  22. if !channel[:options][:folder] || channel[:options][:folder].empty?
  23. @imap.select('INBOX')
  24. else
  25. @imap.select( channel[:options][:folder] )
  26. end
  27. if check_type == 'check'
  28. puts "check only mode, fetch no emails"
  29. disconnect
  30. return
  31. elsif check_type == 'verify'
  32. puts "verify mode, fetch no emails #{verify_string}"
  33. end
  34. count = 0
  35. count_all = @imap.search(['ALL']).count
  36. @imap.search(['ALL']).each do |message_id|
  37. count += 1
  38. puts " - message #{count.to_s}/#{count_all.to_s}"
  39. # puts msg.to_s
  40. # check for verify message
  41. if check_type == 'verify'
  42. subject = @imap.fetch(message_id,'ENVELOPE')[0].attr['ENVELOPE'].subject
  43. if subject && subject =~ /#{verify_string}/
  44. puts " - verify email #{verify_string} found"
  45. @imap.store(message_id, "+FLAGS", [:Deleted])
  46. @imap.expunge()
  47. disconnect
  48. return 'verify ok'
  49. end
  50. else
  51. # delete email from server after article was created
  52. msg = @imap.fetch(message_id,'RFC822')[0].attr['RFC822']
  53. if process(channel, msg)
  54. @imap.store(message_id, "+FLAGS", [:Deleted])
  55. end
  56. end
  57. end
  58. @imap.expunge()
  59. disconnect
  60. if count == 0
  61. puts " - no message"
  62. end
  63. puts "done"
  64. end
  65. def disconnect
  66. if @imap
  67. @imap.disconnect()
  68. end
  69. end
  70. end