Skip to content

Instantly share code, notes, and snippets.

@loopj
Created September 21, 2012 03:09
Show Gist options
  • Save loopj/3759531 to your computer and use it in GitHub Desktop.
Save loopj/3759531 to your computer and use it in GitHub Desktop.
Automatically generates rails plain-text emails from html templates, using premailer
# Automatically generates the plain-text version of emails from the html
# template using premailer.
class SmartMailer < ActionMailer::Base
def mail(headers={})
# Configure the premailer options
premailer_options = {
with_html_string: true,
line_length: 9999,
}
# Pull in body css if available
email_css = Rails.root.join("app", "views", self.class.name.underscore, "email.css")
premailer_options[:css_string] = File.read(email_css) if File.exists?(email_css)
# Render the email in HTML without a layout
html_body = ERB.new(render("#{action_name}", layout: false)).result(binding)
premail = Premailer.new(html_body, premailer_options)
# Render the new plain-text body into the plain-text layout
html_email = render(text: premail.to_inline_css, layout: "#{self.class.name.underscore}")
text_email = render(text: premail.to_plain_text, layout: "#{self.class.name.underscore}", formats: [:text])
super(headers) do |format|
format.text { text_email }
format.html { html_email }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment