Recently, I had to implement an email for the Amaphiko project. And since I won’t code email, at least not in this life, I had to find a workaround. There came MJML.
MJML introduces itself as “the responsive email framework”. Practically speaking, MJML is a markup language built on React that produces email-compliant (whatever that means) markup once compiled.
MJML comes with about 20 components to build simple newsletters (texts, images, links, buttons, columns, tables, etc.) and can be extended by leveraging the power of React for advanced usage.
Setting up MJML in Rails
Amaphiko is a Rails app. Therefore, I needed a way to integrate MJML in the Rails pipeline to be able to produce proper responsive emails based on dynamic data.
While MJML is fairly recent, I was pleased to see there already is a fresh gem to plug it into Rails, called mjml-rails.
First step would be to add it to the Gemfile.
The thing is, this gem is basically just a wrapper around the mjml
npm package. Because of this, it needs mjml
to be installed independently. You can either install it globally to avoid adding a Node.js dependency to your project:
Or if you already use some Node.js modules, you could also just add it to your package.json
file:
Building a MJML-powered email
Let’s create a very simple email through MJML to illustrate this article.
First thing, in app/mailers
, we create a foobar_mailer.rb
file:
Then in app/views
, we create a foobar_mailer
folder, containing a file named after our action baz
. This file has to be a .mjml
file.
That’s it! 🎉
Rendering a MJML partial
When the mail gets a bit long or repetitive, it might be interesting to leverage the power of ERB to have separate files, and render them inside the main template. For instance, each section of the newsletter could live in its own file.
Consider the following header (taken from MJML documentation):
Then in the mail template:
Note that:
- the leading underscore is not necessary;
- the extension can be safely omitted;
- the
formats
property has to be set to[:html]
(not[:mjml]
).
Wrapping things up
MJML is such a fantastic tool to build responsive email newsletters without the hassle and I am super happy to see a proper and simple Rails integration.
No longer will you struggle integrating a newsletter!