lib/mournmail/message_rendering.rb in mournmail-0.3.1 vs lib/mournmail/message_rendering.rb in mournmail-0.3.2

- old
+ new

@@ -1,6 +1,7 @@ require "mail" +require "html2text" module Mournmail module MessageRendering refine ::Mail::Message do def render(indices = []) @@ -25,32 +26,37 @@ end return "[PGP/MIME encrypted message]\n" + mail.render(indices) + sig end if multipart? parts.each_with_index.map { |part, i| - part.render([*indices, i]) + no_content = sub_type == "alternative" && i > 0 + part.render([*indices, i], no_content) }.join - elsif main_type.nil? || (main_type == "text" && sub_type == "plain") - s = body.decoded - Mournmail.to_utf8(s, charset) + elsif main_type.nil? || main_type == "text" + s = Mournmail.to_utf8(body.decoded, charset) + if sub_type == "html" + "[0 text/html]\n" + Html2Text.convert(s) + else + s + end else type = Mail::Encodings.decode_encode(self["content-type"].to_s, :decode) rescue "broken/type; error=\"#{$!} (#{$!.class})\"" - "[-1 #{type}]\n" + "[0 #{type}]\n" end + pgp_signature end def dig_part(i, *rest_indices) if HAVE_MAIL_GPG && encrypted? mail = decrypt(verify: true) return mail.dig_part(i, *rest_indices) end - if i == -1 + if i == 0 return self end - part = parts[i] + part = parts[i - 1] if rest_indices.empty? part else part.dig_part(*rest_indices) end @@ -77,24 +83,25 @@ s + "\n" end end refine ::Mail::Part do - def render(indices) - index = indices.join(".") + def render(indices, no_content = false) + index = indices.map { |i| i + 1 }.join(".") type = Mail::Encodings.decode_encode(self["content-type"].to_s, :decode) rescue "broken/type; error=\"#{$!} (#{$!.class})\"" - "[#{index} #{type}]\n" + render_content(indices) + "[#{index} #{type}]\n" + + (no_content ? "" : render_content(indices)) end def dig_part(i, *rest_indices) if main_type == "message" && sub_type == "rfc822" mail = Mail.new(body.to_s) mail.dig_part(i, *rest_indices) else - part = parts[i] + part = parts[i - 1] if rest_indices.empty? part else part.dig_part(*rest_indices) end @@ -104,19 +111,24 @@ private def render_content(indices) if multipart? parts.each_with_index.map { |part, i| - part.render([*indices, i]) + no_content = sub_type == "alternative" && i > 0 + part.render([*indices, i], no_content) }.join elsif main_type == "message" && sub_type == "rfc822" mail = Mail.new(body.raw_source) mail.render(indices) elsif attachment? "" else - if main_type == "text" && sub_type == "plain" - decoded.sub(/(?<!\n)\z/, "\n").gsub(/\r\n/, "\n") + if main_type == "text" + if sub_type == "html" + Html2Text.convert(decoded).sub(/(?<!\n)\z/, "\n") + else + decoded.sub(/(?<!\n)\z/, "\n").gsub(/\r\n/, "\n") + end else "" end end rescue => e