Auto-generating plain-text bodies for HTML e-mails in Rails apps

Updated . Posted . Visible to the public. Repeats.

When building an application that sends e-mails to users, you want to avoid those e-mails from being classified as spam. Most obvious scoring issues will not be relevant to you because you are not a spammer.

However, your application must do one thing by itself: When sending HTML e-mails, you should include a plain-text body or tools like SpamAssassin will apply a significant score penalty. Here is how to do that automatically.

  1. Add premailer-rails Show archive.org snapshot to your Gemfile and bundle.
  2. Done! premailer-rails will automatically generate a text part for you.

Actually, you may want to configure premailer-rails, and maybe tweak your HTML e-mail views a bit. Here are some suggestions.

  • Open Rails' ActionMailer Previews and you will see a dropdown menu on each e-mail that you can use to switch between plain-text and HTML. Check your text e-mails for any obvious flaws, since some people configure their e-mail clients to prefer a text version and will actually see your new and shiny text e-mail bodies.

  • For configuration, add an initializer at config/initializers/premailer_rails.rb. To increase the default line length, add something like this:

Premailer::Rails.config.merge!(line_length: 80)
  • <hr> tags are not converted by default (as of now). You can add a custom representation like so:
Premailer.prepend(
  Module.new do
    def convert_to_text(html, line_length = 65, from_charset = 'UTF-8')
        html = html.gsub(/<hr[\s]*\/?>/i, "<br>#{'-' * line_length}<br>")
        super(html, line_length, from_charset)
    end
  end
)
  • You may want to strip some whitespace around <br> tags. In Haml templates, simply replace %br with %br>< for that.

  • When you are done, use a spam test service like mail-tester.com to check if all is well.

Note that premailer-rails can do more for you, e.g. insert inline styles from your application's CSS files.

Arne Hartherz
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2019-01-08 16:58)