20240312110258_create_failed_emails.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class CreateFailedEmails < ActiveRecord::Migration[7.0]
  3. OLD_FAILED_EMAIL_DIRECTORY = Rails.root.join('var/spool/unprocessable_mail')
  4. def up
  5. # return if it's a new setup
  6. return if !Setting.exists?(name: 'system_init_done')
  7. create_table :failed_emails do |t|
  8. t.binary :data, null: false
  9. t.integer :retries, null: false, default: 1
  10. t.text :parsing_error
  11. t.timestamps limit: 3, null: false
  12. end
  13. return if !Dir.exist?(OLD_FAILED_EMAIL_DIRECTORY)
  14. import_emails
  15. remove_old_unprocessable_emails
  16. end
  17. def down
  18. drop_table :failed_emails
  19. end
  20. private
  21. def remove_old_unprocessable_emails
  22. FileUtils.rm_rf OLD_FAILED_EMAIL_DIRECTORY
  23. rescue # handle read-only file systems gracefully
  24. nil
  25. end
  26. def import_emails
  27. Dir.each_child(OLD_FAILED_EMAIL_DIRECTORY) do |filename|
  28. next if !filename.ends_with? '.eml'
  29. import_single_email(filename)
  30. end
  31. end
  32. def import_single_email(filename)
  33. path = OLD_FAILED_EMAIL_DIRECTORY.join(filename)
  34. data = File.binread(path)
  35. FailedEmail.create(data:)
  36. end
  37. end