Created
September 21, 2012 03:09
-
-
Save loopj/3759531 to your computer and use it in GitHub Desktop.
Automatically generates rails plain-text emails from html templates, using premailer
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
# 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