3

I have a rails 2.3 application and would like to integrate the premailer gem to it. I found how can you do it for a rails 3.X application: How to Integrate 'premailer' with Rails Anyone knows how to do it for action mailer 2.3.10?

Community
  • 1
  • 1
iwiznia
  • 1,669
  • 14
  • 21

1 Answers1

3

I've spent a good chunk of the last couple of days on this now and it seems there is no great solution. It is possible to render the message explicitly and then pass the result through Premailer, but it gets messy in combination with multipart emails and HTML layouts and if the template uses some other encoding than ASCII-8BIT.

In a straight HTML email without multiparts and assuming an ASCII-8BIT encoded template, this works for me:

def some_email
    recipients   "Reciever <reciever@example.com>"
    from         "Sender <sender@example.com>"
    subject      "Hello"
    content_type "text/html"

    message = render_message("some_email", { }) # second argument is a hash of locals
    p.body = Premailer.new(message, with_html_string: true).to_inline_css
end

However, if the template is encoded with some other encoding than ASCII-8BIT, Premailer destroys all non-ASCII characters. There is a fix merged into the Premailer repo, but no version has been released since. Using the latest revision and calling Premailer.new(message, with_html_string: true, input_encoding: "UTF-8").to_inline_css or similar should work. The merge commit is https://github.com/alexdunae/premailer/commit/5f5cbb4ac181299a7e73d3eca11f3cf546585364.

In the case of multipart emails I haven't really gotten ActionMailer to use the correct content types internally for rendering the templates. This results in the implicit typing via template file names not working and, as a result, layouts being incorrectly applied to text versions. A workaround for this would be to explicitly use no layout for the text version, resulting in something like this (note the template names):

def some_multipart_email
    recipients   "Reciever <reciever@example.com>"
    from         "Sender <sender@example.com>"
    subject      "Hello"
    content_type "text/html"

    part "text/html" do |p|
        message = render_message("some_email_html", { })
        p.body = Premailer.new(message, with_html_string: true).to_inline_css
    end

    part "text/plain" do |p|
        p.content_type = "text/plain"
        p.body = render(file: "some_email_text", body: { }, layout: false)
    end
end
stefanlindbohm
  • 343
  • 3
  • 9