Read more

HTML emails with inline stylesheets and webpacker

Natalie Zeumann
April 12, 2019Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Natalie Zeumann to makandra dev (2019-04-12 14:06)