HTML emails with inline stylesheets and webpacker

Updated . Posted . Visible to the public.

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 Show archive.org snapshot or premailer Show archive.org snapshot , 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:

gem 'premailer-rails'

In your ApplicationMailer define the mailer layout:

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:

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

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

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

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

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:

<%= 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.

Natalie Zeumann
Last edit
Natalie Zeumann
License
Source code in this card is licensed under the MIT License.
Posted by Natalie Zeumann to makandra dev (2019-04-12 12:06)