Skip to content

Instantly share code, notes, and snippets.

@dpaluy
Created January 8, 2024 02:57
Show Gist options
  • Save dpaluy/e170b74f107f86ba905abdeed0493778 to your computer and use it in GitHub Desktop.
Save dpaluy/e170b74f107f86ba905abdeed0493778 to your computer and use it in GitHub Desktop.
Rails HTML Email to Text
class ApplicationMailer < ActionMailer::Base
using Refinements::Mailings
protected
def render_text_for(template_name)
text = render_to_string(template_name, formats: :html).html_to_plain
render(plain: text)
end
end
class MyMailer < ApplicationMailer
def welcome_email
mail(subject: "Welcome") do |format|
format.html
format.text { render_text_for(__method__) }
end
end
end
module Refinements::Mailings
refine String do
def html_to_plain
preprocessed = self
.gsub("<hr>", "\n--- --- --- --- --- --- --- --- --- --- --- ---\n")
.gsub(/<br\\?>/, " ") # line breaks
.gsub(/<li[^>]*>/, "- ") # lists
.gsub(/<\/t[hd]>\s*<t[hd][^>]*>/, " | ") # table cells (tr and table tags are removed later)
return ActionController::Base.helpers.strip_tags(preprocessed)
.split("\n").map(&:strip).join("\n") # fix indentation
.gsub("\n\n\n", "\n") # remove extensive new lines
.strip
end
end
end
@dpaluy
Copy link
Author

dpaluy commented Jan 8, 2024

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