# frozen_string_literal: true class EmailImporter attr_accessor :email_class attr_accessor :html_to_text_class def initialize( email_class: Email, html_to_text_class: Rails.configuration.html_to_text_class) @email_class = email_class @html_to_text_class = html_to_text_class end def import(mail) email = email_class.new( message_id: mail.message_id, subject: mail.subject, date: mail.date, to: mail.to, delivered_to: delivered_to(mail), from: mail.from, plain_body: text_plain_body(mail), headers: hashed_headers(mail) ) rescue => ex binding.pry end def delivered_to(mail) values_from_header(header: mail.header["Delivered-To"], default: Array(mail.to)) end def text_plain_body(mail) if mail.parts.present? if mail.text_part.present? mail.text_part.decoded elsif mail.html_part.present? html_to_text_class.new.convert(mail.html_part.decoded) else mail.parts[0].decoded end elsif mail.content_type && mail.content_type.match?(/\btext\/html\b/) plain_text = html_to_text_class.new.convert(mail.decoded) if mail.content_type.match?(/\butf-8\b/i) and !plain_text.valid_encoding? plain_text.encode('UTF-8', 'binary', invalid: :replace, undef: :replace) else plain_text end else mail.decoded end end def hashed_headers(mail) mail.header.map { |header| { "name" => header.name, "value" => header.value } } end def values_from_header(header:, default: []) if header.respond_to?(:map) header.map(&:value) elsif header.respond_to?(:value) Array(header.value) elsif block_given? yield(header) else default end end end