imap.rb 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. # Copyright (C) 2012-2025 Zammad Foundation, https://zammad-foundation.org/
  2. require 'net/imap'
  3. class Channel::Driver::Imap < Channel::Driver::BaseEmailInbound
  4. FETCH_METADATA_TIMEOUT = 2.minutes
  5. FETCH_MSG_TIMEOUT = 4.minutes
  6. EXPUNGE_TIMEOUT = 16.minutes
  7. DEFAULT_TIMEOUT = 45.seconds
  8. CHECK_ONLY_TIMEOUT = 8.seconds
  9. =begin
  10. fetch emails from IMAP account
  11. instance = Channel::Driver::Imap.new
  12. result = instance.fetch(params[:inbound][:options], channel, 'verify', subject_looking_for)
  13. returns
  14. {
  15. result: 'ok',
  16. fetched: 123,
  17. notice: 'e. g. message about to big emails in mailbox',
  18. }
  19. check if connect to IMAP account is possible, return count of mails in mailbox
  20. instance = Channel::Driver::Imap.new
  21. result = instance.fetch(params[:inbound][:options], channel, 'check')
  22. returns
  23. {
  24. result: 'ok',
  25. content_messages: 123,
  26. }
  27. verify IMAP account, check if search email is in there
  28. instance = Channel::Driver::Imap.new
  29. result = instance.fetch(params[:inbound][:options], channel, 'verify', subject_looking_for)
  30. returns
  31. {
  32. result: 'ok', # 'verify not ok'
  33. }
  34. example
  35. params = {
  36. host: 'outlook.office365.com',
  37. user: 'xxx@zammad.onmicrosoft.com',
  38. password: 'xxx',
  39. keep_on_server: true,
  40. }
  41. OR
  42. params = {
  43. host: 'imap.gmail.com',
  44. user: 'xxx@gmail.com',
  45. password: 'xxx',
  46. keep_on_server: true,
  47. auth_type: 'XOAUTH2'
  48. }
  49. channel = Channel.last
  50. instance = Channel::Driver::Imap.new
  51. result = instance.fetch(params, channel, 'verify')
  52. =end
  53. def fetch(options, channel)
  54. setup_connection(options)
  55. keep_on_server = false
  56. if [true, 'true'].include?(options[:keep_on_server])
  57. keep_on_server = true
  58. end
  59. message_ids_result = Timeout.timeout(6.minutes) do
  60. if keep_on_server
  61. fetch_unread_message_ids
  62. else
  63. fetch_all_message_ids
  64. end
  65. end
  66. message_ids = message_ids_result[:result]
  67. # fetch regular messages
  68. count_all = message_ids.count
  69. count = 0
  70. count_fetched = 0
  71. count_max = 5000
  72. too_large_messages = []
  73. active_check_interval = 20
  74. result = 'ok'
  75. notice = ''
  76. message_ids.each do |message_id|
  77. count += 1
  78. break if (count % active_check_interval).zero? && channel_has_changed?(channel)
  79. break if max_process_count_was_reached?(channel, count, count_max)
  80. Rails.logger.info " - message #{count}/#{count_all}"
  81. message_meta = nil
  82. Timeout.timeout(FETCH_METADATA_TIMEOUT) do
  83. message_meta = @imap.fetch(message_id, ['RFC822.SIZE', 'FLAGS', 'INTERNALDATE', 'RFC822.HEADER'])[0]
  84. rescue Net::IMAP::ResponseParseError => e
  85. raise if e.message.exclude?('unknown token')
  86. result = 'error'
  87. notice += <<~NOTICE
  88. One of your incoming emails could not be imported (#{e.message}).
  89. Please remove it from your inbox directly
  90. to prevent Zammad from trying to import it again.
  91. NOTICE
  92. Rails.logger.error "Net::IMAP failed to parse message #{message_id}: #{e.message} (#{e.class})"
  93. Rails.logger.error '(See https://github.com/zammad/zammad/issues/2754 for more details)'
  94. end
  95. next if message_meta.nil?
  96. # ignore verify messages
  97. next if !messages_is_too_old_verify?(self.class.extract_rfc822_headers(message_meta), count, count_all)
  98. # ignore deleted messages
  99. next if deleted?(message_meta, count, count_all)
  100. # ignore already imported
  101. if already_imported?(self.class.extract_rfc822_headers(message_meta), keep_on_server, channel)
  102. Timeout.timeout(1.minute) do
  103. @imap.store(message_id, '+FLAGS', [:Seen])
  104. end
  105. Rails.logger.info " - ignore message #{count}/#{count_all} - because message message id already imported"
  106. next
  107. end
  108. # delete email from server after article was created
  109. msg = nil
  110. begin
  111. Timeout.timeout(FETCH_MSG_TIMEOUT) do
  112. key = fetch_message_body_key(options)
  113. msg = @imap.fetch(message_id, key)[0].attr[key]
  114. end
  115. rescue Timeout::Error => e
  116. Rails.logger.error "Unable to fetch email from #{count}/#{count_all} from server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  117. raise e
  118. end
  119. next if !msg
  120. # do not process too big messages, instead download & send postmaster reply
  121. too_large_info = too_large?(message_meta.attr['RFC822.SIZE'])
  122. if too_large_info
  123. if Setting.get('postmaster_send_reject_if_mail_too_large') == true
  124. info = " - download message #{count}/#{count_all} - ignore message because it's too large (is:#{too_large_info[0]} MB/max:#{too_large_info[1]} MB)"
  125. Rails.logger.info info
  126. notice += "#{info}\n"
  127. process_oversized_mail(channel, msg)
  128. else
  129. info = " - ignore message #{count}/#{count_all} - because message is too large (is:#{too_large_info[0]} MB/max:#{too_large_info[1]} MB)"
  130. Rails.logger.info info
  131. notice += "#{info}\n"
  132. too_large_messages.push info
  133. next
  134. end
  135. else
  136. process(channel, msg, false)
  137. end
  138. begin
  139. Timeout.timeout(FETCH_MSG_TIMEOUT) do
  140. if keep_on_server
  141. @imap.store(message_id, '+FLAGS', [:Seen])
  142. else
  143. @imap.store(message_id, '+FLAGS', [:Deleted])
  144. end
  145. end
  146. rescue Timeout::Error => e
  147. Rails.logger.error "Unable to set +FLAGS for email #{count}/#{count_all} on server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  148. raise e
  149. end
  150. count_fetched += 1
  151. end
  152. if !keep_on_server
  153. begin
  154. Timeout.timeout(EXPUNGE_TIMEOUT) do
  155. @imap.expunge
  156. end
  157. rescue Timeout::Error => e
  158. Rails.logger.error "Unable to expunge server (#{options[:host]}/#{options[:user]}): #{e.inspect}"
  159. raise e
  160. end
  161. end
  162. disconnect
  163. if count.zero?
  164. Rails.logger.info ' - no message'
  165. end
  166. # Error is raised if one of the messages was too large AND postmaster_send_reject_if_mail_too_large is turned off.
  167. # This effectivelly marks channels as stuck and gets highlighted for the admin.
  168. # New emails are still processed! But large email is not touched, so error keeps being re-raised on every fetch.
  169. if too_large_messages.present?
  170. raise too_large_messages.join("\n")
  171. end
  172. {
  173. result: result,
  174. fetched: count_fetched,
  175. notice: notice,
  176. }
  177. end
  178. # Checks if mailbox has anything besides Zammad verification emails.
  179. # If any real messages exists, return the real count including messages to be ignored when importing.
  180. # If only verification messages found, return 0.
  181. def check_configuration(options)
  182. setup_connection(options, check: true)
  183. message_ids_result = Timeout.timeout(6.minutes) do
  184. fetch_all_message_ids
  185. end
  186. message_ids = message_ids_result[:result]
  187. Rails.logger.info 'check only mode, fetch no emails'
  188. has_content_messages = message_ids
  189. .first(5000)
  190. .any? do |message_id|
  191. message_meta = Timeout.timeout(1.minute) do
  192. @imap.fetch(message_id, ['RFC822.HEADER'])[0]
  193. end
  194. # check how many content messages we have, for notice used
  195. headers = self.class.extract_rfc822_headers(message_meta)
  196. !messages_is_verify_message?(headers) && !messages_is_ignore_message?(headers)
  197. end
  198. disconnect
  199. {
  200. result: 'ok',
  201. content_messages: has_content_messages ? message_ids.count : 0,
  202. }
  203. end
  204. # This method is used for custom IMAP only.
  205. # It is not used in conjunction with Micrsofot365 or Gogle OAuth channels.
  206. def verify(options, verify_string)
  207. setup_connection(options)
  208. message_ids_result = Timeout.timeout(6.minutes) do
  209. fetch_all_message_ids
  210. end
  211. message_ids = message_ids_result[:result]
  212. Rails.logger.info "verify mode, fetch no emails #{verify_string}"
  213. # check for verify message
  214. message_ids.reverse_each do |message_id|
  215. message_meta = nil
  216. Timeout.timeout(FETCH_METADATA_TIMEOUT) do
  217. message_meta = @imap.fetch(message_id, ['RFC822.HEADER'])[0]
  218. end
  219. # check if verify message exists
  220. headers = self.class.extract_rfc822_headers(message_meta)
  221. subject = headers['Subject']
  222. next if !subject
  223. next if !subject.match?(%r{#{verify_string}})
  224. Rails.logger.info " - verify email #{verify_string} found"
  225. Timeout.timeout(600) do
  226. @imap.store(message_id, '+FLAGS', [:Deleted])
  227. @imap.expunge
  228. end
  229. disconnect
  230. return {
  231. result: 'ok',
  232. }
  233. end
  234. disconnect
  235. {
  236. result: 'verify not ok',
  237. }
  238. end
  239. def fetch_all_message_ids
  240. fetch_message_ids %w[ALL]
  241. end
  242. def fetch_unread_message_ids
  243. fetch_message_ids %w[NOT SEEN]
  244. rescue
  245. fetch_message_ids %w[UNSEEN]
  246. end
  247. def fetch_message_ids(filter)
  248. raise if @imap.capabilities.exclude?('SORT')
  249. {
  250. result: @imap.sort(['DATE'], filter, 'US-ASCII'),
  251. is_fallback: false
  252. }
  253. rescue
  254. {
  255. result: @imap.search(filter),
  256. is_fallback: true # indicates that we can not use a result ordered by date
  257. }
  258. end
  259. def fetch_message_body_key(options)
  260. # https://github.com/zammad/zammad/issues/4589
  261. options['host'] == 'imap.mail.me.com' ? 'BODY[]' : 'RFC822'
  262. end
  263. def disconnect
  264. return if !@imap
  265. Timeout.timeout(1.minute) do
  266. @imap.disconnect
  267. end
  268. end
  269. # Parses RFC822 header
  270. # @param [String] RFC822 header text blob
  271. # @return [Hash<String=>String>]
  272. def self.parse_rfc822_headers(string)
  273. array = string
  274. .gsub("\r\n\t", ' ') # Some servers (e.g. microsoft365) may put attribute value on a separate line and tab it
  275. .lines(chomp: true)
  276. .map { |line| line.split(%r{:\s*}, 2).map(&:strip) }
  277. array.each { |elem| elem.append(nil) if elem.one? }
  278. Hash[*array.flatten]
  279. end
  280. # Parses RFC822 header
  281. # @param [Net::IMAP::FetchData] fetched message
  282. # @return [Hash<String=>String>]
  283. def self.extract_rfc822_headers(message_meta)
  284. blob = message_meta&.attr&.dig 'RFC822.HEADER'
  285. return if !blob
  286. parse_rfc822_headers blob
  287. end
  288. private
  289. =begin
  290. check if email is already marked as deleted
  291. Channel::Driver::IMAP.deleted?(message_meta, count, count_all)
  292. returns
  293. true|false
  294. =end
  295. def deleted?(message_meta, count, count_all)
  296. return false if message_meta.attr['FLAGS'].exclude?(:Deleted)
  297. Rails.logger.info " - ignore message #{count}/#{count_all} - because message has already delete flag"
  298. true
  299. end
  300. =begin
  301. check if maximal fetching email count has reached
  302. Channel::Driver::IMAP.max_process_count_was_reached?(channel, count, count_max)
  303. returns
  304. true|false
  305. =end
  306. def max_process_count_was_reached?(channel, count, count_max)
  307. return false if count < count_max
  308. Rails.logger.info "Maximal fetched emails (#{count_max}) reached for this interval for Channel with id #{channel.id}."
  309. true
  310. end
  311. def setup_connection(options, check: false)
  312. ssl = true
  313. ssl_verify = options.fetch(:ssl_verify, true)
  314. starttls = false
  315. keep_on_server = false
  316. folder = 'INBOX'
  317. if [true, 'true'].include?(options[:keep_on_server])
  318. keep_on_server = true
  319. end
  320. case options[:ssl]
  321. when 'off'
  322. ssl = false
  323. when 'starttls'
  324. ssl = false
  325. starttls = true
  326. end
  327. port = if options.key?(:port) && options[:port].present?
  328. options[:port].to_i
  329. elsif ssl == true
  330. 993
  331. else
  332. 143
  333. end
  334. if options[:folder].present?
  335. folder = options[:folder]
  336. end
  337. Rails.logger.info "fetching imap (#{options[:host]}/#{options[:user]} port=#{port},ssl=#{ssl},starttls=#{starttls},folder=#{folder},keep_on_server=#{keep_on_server},auth_type=#{options.fetch(:auth_type, 'LOGIN')})"
  338. # on check, reduce open_timeout to have faster probing
  339. check_type_timeout = check ? CHECK_ONLY_TIMEOUT : DEFAULT_TIMEOUT
  340. Certificate::ApplySSLCertificates.ensure_fresh_ssl_context if ssl || starttls
  341. Timeout.timeout(check_type_timeout) do
  342. ssl_settings = false
  343. ssl_settings = (ssl_verify ? true : { verify_mode: OpenSSL::SSL::VERIFY_NONE }) if ssl
  344. @imap = ::Net::IMAP.new(options[:host], port: port, ssl: ssl_settings)
  345. if starttls
  346. @imap.starttls(verify_mode: ssl_verify ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE)
  347. end
  348. end
  349. Timeout.timeout(check_type_timeout) do
  350. if options[:auth_type].present?
  351. @imap.authenticate(options[:auth_type], options[:user], options[:password])
  352. else
  353. @imap.login(options[:user], options[:password].dup&.force_encoding('ascii-8bit'))
  354. end
  355. end
  356. Timeout.timeout(check_type_timeout) do
  357. # select folder
  358. @imap.select(folder)
  359. end
  360. end
  361. end