imap.rb 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. require 'net/imap'
  3. class Channel::Driver::Imap < Channel::EmailParser
  4. def fetchable?(_channel)
  5. true
  6. end
  7. =begin
  8. fetch emails from IMAP account
  9. instance = Channel::Driver::Imap.new
  10. result = instance.fetch(params[:inbound][:options], channel, 'verify', subject_looking_for)
  11. returns
  12. {
  13. result: 'ok',
  14. fetched: 123,
  15. notice: 'e. g. message about to big emails in mailbox',
  16. }
  17. check if connect to IMAP account is possible, return count of mails in mailbox
  18. instance = Channel::Driver::Imap.new
  19. result = instance.fetch(params[:inbound][:options], channel, 'check')
  20. returns
  21. {
  22. result: 'ok',
  23. content_messages: 123,
  24. }
  25. verify IMAP account, check if search email is in there
  26. instance = Channel::Driver::Imap.new
  27. result = instance.fetch(params[:inbound][:options], channel, 'verify', subject_looking_for)
  28. returns
  29. {
  30. result: 'ok', # 'verify not ok'
  31. }
  32. example
  33. params = {
  34. host: 'outlook.office365.com',
  35. user: 'xxx@znuny.onmicrosoft.com',
  36. password: 'xxx',
  37. keep_on_server: true,
  38. }
  39. channel = Channel.last
  40. instance = Channel::Driver::Imap.new
  41. result = instance.fetch(params, channel, 'verify')
  42. =end
  43. def fetch(options, channel, check_type = '', verify_string = '')
  44. ssl = true
  45. port = 993
  46. keep_on_server = false
  47. folder = 'INBOX'
  48. if options[:keep_on_server] == true || options[:keep_on_server] == 'true'
  49. keep_on_server = true
  50. end
  51. if options.key?(:ssl) && options[:ssl] == false
  52. ssl = false
  53. port = 143
  54. end
  55. if options.key?(:port) && options[:port].present?
  56. port = options[:port]
  57. # disable ssl for non ssl ports
  58. if port == 143 && !options.key?(:ssl)
  59. ssl = false
  60. end
  61. end
  62. if options[:folder].present?
  63. folder = options[:folder]
  64. end
  65. Rails.logger.info "fetching imap (#{options[:host]}/#{options[:user]} port=#{port},ssl=#{ssl},folder=#{folder},keep_on_server=#{keep_on_server})"
  66. # on check, reduce open_timeout to have faster probing
  67. timeout = 45
  68. if check_type == 'check'
  69. timeout = 6
  70. end
  71. Timeout.timeout(timeout) do
  72. @imap = Net::IMAP.new(options[:host], port, ssl, nil, false)
  73. end
  74. @imap.login(options[:user], options[:password])
  75. # select folder
  76. @imap.select(folder)
  77. # sort messages by date on server (if not supported), if not fetch messages via search (first in, first out)
  78. filter = ['ALL']
  79. if keep_on_server && check_type != 'check' && check_type != 'verify'
  80. filter = %w(NOT SEEN)
  81. end
  82. begin
  83. message_ids = @imap.sort(['DATE'], filter, 'US-ASCII')
  84. rescue
  85. message_ids = @imap.search(filter)
  86. end
  87. # check mode only
  88. if check_type == 'check'
  89. Rails.logger.info 'check only mode, fetch no emails'
  90. content_max_check = 2
  91. content_messages = 0
  92. # check messages
  93. message_ids.each do |message_id|
  94. message_meta = @imap.fetch(message_id, ['RFC822.HEADER'])[0].attr
  95. # check how many content messages we have, for notice used
  96. header = message_meta['RFC822.HEADER']
  97. if header && header !~ /x-zammad-ignore/i
  98. content_messages += 1
  99. break if content_max_check < content_messages
  100. end
  101. end
  102. if content_messages >= content_max_check
  103. content_messages = message_ids.count
  104. end
  105. disconnect
  106. return {
  107. result: 'ok',
  108. content_messages: content_messages,
  109. }
  110. end
  111. # reverse message order to increase performance
  112. if check_type == 'verify'
  113. Rails.logger.info "verify mode, fetch no emails #{verify_string}"
  114. message_ids.reverse!
  115. # check for verify message
  116. message_ids.each do |message_id|
  117. message_meta = @imap.fetch(message_id, ['ENVELOPE'])[0].attr
  118. # check if verify message exists
  119. subject = message_meta['ENVELOPE'].subject
  120. next if !subject
  121. next if subject !~ /#{verify_string}/
  122. Rails.logger.info " - verify email #{verify_string} found"
  123. @imap.store(message_id, '+FLAGS', [:Deleted])
  124. @imap.expunge()
  125. disconnect
  126. return {
  127. result: 'ok',
  128. }
  129. end
  130. disconnect
  131. return {
  132. result: 'verify not ok',
  133. }
  134. end
  135. # fetch regular messages
  136. count_all = message_ids.count
  137. count = 0
  138. count_fetched = 0
  139. notice = ''
  140. message_ids.each do |message_id|
  141. count += 1
  142. Rails.logger.info " - message #{count}/#{count_all}"
  143. message_meta = @imap.fetch(message_id, ['RFC822.SIZE', 'ENVELOPE', 'FLAGS', 'INTERNALDATE'])[0]
  144. # ignore to big messages
  145. info = too_big?(message_meta, count, count_all)
  146. if info
  147. notice += "#{info}\n"
  148. next
  149. end
  150. # ignore deleted messages
  151. next if deleted?(message_meta, count, count_all)
  152. # ignore already imported
  153. next if already_imported?(message_id, message_meta, count, count_all, keep_on_server, channel)
  154. # delete email from server after article was created
  155. msg = @imap.fetch(message_id, 'RFC822')[0].attr['RFC822']
  156. next if !msg
  157. process(channel, msg, false)
  158. if !keep_on_server
  159. @imap.store(message_id, '+FLAGS', [:Deleted])
  160. else
  161. @imap.store(message_id, '+FLAGS', [:Seen])
  162. end
  163. count_fetched += 1
  164. end
  165. if !keep_on_server
  166. @imap.expunge()
  167. end
  168. disconnect
  169. if count.zero?
  170. Rails.logger.info ' - no message'
  171. end
  172. Rails.logger.info 'done'
  173. {
  174. result: 'ok',
  175. fetched: count_fetched,
  176. notice: notice,
  177. }
  178. end
  179. def disconnect
  180. return if !@imap
  181. @imap.disconnect()
  182. end
  183. =begin
  184. Channel::Driver::Imap.streamable?
  185. returns
  186. true|false
  187. =end
  188. def self.streamable?
  189. false
  190. end
  191. private
  192. # rubocop:disable Metrics/ParameterLists
  193. def already_imported?(message_id, message_meta, count, count_all, keep_on_server, channel)
  194. # rubocop:enable Metrics/ParameterLists
  195. return false if !keep_on_server
  196. return false if !message_meta.attr
  197. return false if !message_meta.attr['ENVELOPE']
  198. local_message_id = message_meta.attr['ENVELOPE'].message_id
  199. return false if local_message_id.blank?
  200. local_message_id_md5 = Digest::MD5.hexdigest(local_message_id)
  201. article = Ticket::Article.where(message_id_md5: local_message_id_md5).order('created_at DESC, id DESC').limit(1).first
  202. return false if !article
  203. # verify if message is already imported via same channel, if not, import it again
  204. ticket = article.ticket
  205. if ticket && ticket.preferences && ticket.preferences[:channel_id].present? && channel.present?
  206. return false if ticket.preferences[:channel_id] != channel[:id]
  207. end
  208. @imap.store(message_id, '+FLAGS', [:Seen])
  209. Rails.logger.info " - ignore message #{count}/#{count_all} - because message message id already imported"
  210. true
  211. end
  212. def deleted?(message_meta, count, count_all)
  213. return false if !message_meta.attr['FLAGS'].include?(:Deleted)
  214. Rails.logger.info " - ignore message #{count}/#{count_all} - because message has already delete flag"
  215. true
  216. end
  217. def too_big?(message_meta, count, count_all)
  218. max_message_size = Setting.get('postmaster_max_size').to_f
  219. real_message_size = message_meta.attr['RFC822.SIZE'].to_f / 1024 / 1024
  220. if real_message_size > max_message_size
  221. info = " - ignore message #{count}/#{count_all} - because message is too big (is:#{real_message_size} MB/max:#{max_message_size} MB)"
  222. Rails.logger.info info
  223. return info
  224. end
  225. false
  226. end
  227. end