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
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
app/views, we create a
foobar_mailer folder, containing a file named after our action
baz. This file has to be a
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:
- the leading underscore is not necessary;
- the extension can be safely omitted;
formatsproperty has to be set to
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!