Posted 3 months ago. Visible to the public.

HTML emails with inline stylesheets and webpacker

Many mail clients do not support external style sheets. Some even require all styling inline, which means you'll have to do your styling inline. For Rails applications, you can use Roadie or premailer, which lets you keep your well-structured CSS files and do the inlining for you.

See Designing HTML email

Since Roadie is now in passive maintenance mode, we go with premailer:

Include premailer in your Gemfile:

Copy
gem 'premailer-rails'

In your ApplicationMailer define the mailer layout:

Copy
layout 'mailer'

To get the mailer stylesheet (and only the mailer stylesheet) we have a separated mailer.js in webpack/packs where we include the css file für our mail styles:

Copy
import '../application/stylesheets/mailer.sass'

In your mailer.html.erb you can now simply include the stylesheet tag via:

Copy
<head> ... <%= stylesheet_pack_tag 'mailer', media: 'all' %> </head>

If you need images inline those images in your mail method:

Copy
def test_email(recipient, current_user) attachments.inline['logo.png'] = File.read(company.logo.thumb.path) mail(to: recipient, subject: 'My pretty e-mail') end

And you can simply include them in the e-mail template:

Copy
<%= image_tag attachments['logo.png'].url, alt: 'Company logo', width: 100 %>

Note: You should set the html width and/or height attribute as shown above, because most of the e-mail clients can understand it (unlike css width or height styles)

Make sure you are not sending big images. Go with thumb versions.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Natalie Krehan
Last edit:
3 months ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Natalie Krehan to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more