Posted 6 months 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:

    Copy
    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:

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

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
5 months 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 cookies to improve usability and analyze traffic.
Accept or learn more