Created
January 8, 2024 02:57
-
-
Save dpaluy/e170b74f107f86ba905abdeed0493778 to your computer and use it in GitHub Desktop.
Rails HTML Email to Text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyMailer < ApplicationMailer | |
def welcome_email | |
mail(subject: "Welcome") do |format| | |
format.html | |
format.text { render_text_for(__method__) } | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source: https://www.netskin.com/posts/20230716-autogenerate-plain-email-version