Sha256: f2abb25a2218ee065876769bc2b17b7d931144ab68e45d522a89a30fdefe6077

Contents?: true

Size: 1.01 KB

Versions: 8

Compression:

Stored size: 1.01 KB

Contents

require 'nokogiri'

module Spreewald
  class MailToPlaintextConverter
    def initialize(mail, type = '')
      @mail = mail
      @type = type
    end
  
    def run
      body = ''
      if mail.multipart?
        body = if mail.html_part && type != 'plain-text'
          text_from_html(mail.html_part.body.to_s)
        elsif mail.text_part && type != 'HTML'
          mail.text_part.body.to_s
        else
          mail.body.to_s
        end
      else
        if body_text_html?
          body = text_from_html(mail.body.to_s)
        else
          body = mail.body.to_s
        end
      end
      body.gsub("\r\n", "\n") # The mail gem (>= 2.7.1) switched from \n to \r\n line breaks (LF to CRLF) in plain text mails.
    end
  
    private
  
    attr_reader :mail, :type
  
    def body_text_html?
      mail.body.to_s.include? "<html>"
    end
  
    def text_from_html(html)
      Nokogiri::HTML(html)
        .at_css('body')
        .text
        .gsub(/[\r\n]+/, "\n")
        .gsub(/\n\s+/, "\n")
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
spreewald-4.6.3 lib/spreewald_support/mail_to_plaintext_converter.rb
spreewald-4.6.2 lib/spreewald_support/mail_to_plaintext_converter.rb
spreewald-4.6.1 lib/spreewald_support/mail_to_plaintext_converter.rb
spreewald-4.6.0 lib/spreewald_support/mail_to_plaintext_converter.rb
spreewald-4.5.1 lib/spreewald_support/mail_to_plaintext_converter.rb
spreewald-4.5.0 lib/spreewald_support/mail_to_plaintext_converter.rb
spreewald-4.4.4 lib/spreewald_support/mail_to_plaintext_converter.rb
spreewald-4.4.3 lib/spreewald_support/mail_to_plaintext_converter.rb