require 'sanitize' require 'cgi' module Ag::Rendering class HTMLizer def self.HTMLize(mail) if mail.multipart? content_type = mime_split(mail.parts.first.content_type) if content_type == 'text/plain' || content_type == 'text/html' to_content(content_type, mail.parts.first.decoded, get_encoding(mail.parts.first)) else # Nested multipart? if mail.parts.first.multipart? content_type = mime_split(mail.parts.first.parts.first.content_type) if content_type == 'text/plain' || content_type == 'text/html' to_content(content_type, mail.parts.first.parts.first.decoded, get_encoding(mail.parts.first.parts.first)) else raise "Cannot find body: #{mail.message_id}" end # Specialty: Gnus/Emacs signed emails with no explicit multipart type elsif mime_split(mail.content_type) == 'multipart/signed' to_content('text/plain', mail.parts.first.decoded, get_encoding(mail.parts.first)) end end else # No Content-Type, assume plain text (git-send-email) if mail.content_type.nil? to_content('text/plain', mail.body.decoded, get_encoding(mail)) else to_content(mime_split(mail.content_type), mail.body.decoded, get_encoding(mail)) end end end def self.get_encoding(part) part.content_type_parameters['charset'] if part.content_type_parameters end def self.to_content(content_type, content, _charset = nil) # content = content.force_encoding(charset) if charset if content_type == 'text/plain' escaped_content = CGI.escapeHTML(content) escaped_content.lines.map do |line| if line.start_with? '>' "
#{line.rstrip}
\n" else line end end.join.gsub("\n
", "\n") elsif content_type == 'text/html' '
' + Sanitize.fragment(content, Sanitize::Config::BASIC) + '
' else '' end end def self.mime_split(content_type) (content_type || '').split(';').first end end end # vim: ts=2 sts=2 et ft=ruby: