Skip to content

Instantly share code, notes, and snippets.

@loopj
Created September 21, 2012 03:09
Show Gist options
  • Select an option

  • Save loopj/3759531 to your computer and use it in GitHub Desktop.

Select an option

Save loopj/3759531 to your computer and use it in GitHub Desktop.

Revisions

  1. loopj created this gist Sep 21, 2012.
    29 changes: 29 additions & 0 deletions smart-mailer.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    # 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