Posted about 2 years ago. Visible to the public. Repeats.

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

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 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( 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 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.

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Arne Hartherz
Last edit:
about 2 years ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more