Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nateberkopec/4353214 to your computer and use it in GitHub Desktop.
Save nateberkopec/4353214 to your computer and use it in GitHub Desktop.
Rails 4 edition
#
# Insert an automatic text MIME part into HTML e-mail.
# (c) Daniel Doubrovkine, Art.sy 2012
# MIT License
#
class ActionMailerWithTextPart < ActionMailer::Base
def collect_responses(headers)
responses = super(headers)
html_part = responses.detect { |response| response[:content_type] == "text/html" }
text_part = responses.detect { |response| response[:content_type] == "text/plain" }
if html_part && ! text_part
body_parts = []
Nokogiri::HTML(html_part[:body]).traverse do |node|
if node.text? and ! (content = node.content ? node.content.strip : nil).blank?
body_parts << content
elsif node.name == "a" && (href = node.attr("href")) && href.match(/^https?:/)
body_parts << href
end
end
responses.insert 0, { content_type: "text/plain", body: body_parts.uniq.join("\n") }
end
[responses]
end
end
@christiangenco
Copy link

When I ran this, I got: ArgumentError: Header names may not contain a colon. Changing line 23 to just responses did the trick (from @dblock).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment