Read more

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

Arne Hartherz
January 08, 2019Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2019-01-08 17:58)