Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting External CSS to Inline CSS for Mail in Rails

I am trying to create an application that will send out style-heavy emails and have required clients working except Google's Gmail. I researched the issue and it looks like Gmail strips out CSS from external files or CSS nested in the 'style' tag. Does an easy way exist of moving style from an external file to being inline?

Something that will take:

<style>
.wide { width: 100px; }
.cell { display: block; }
</style>
<span class="wide cell">Sample</span>

And convert it to:

<div class="wide cell" style="width: 100px; display: block;">Sample</div>

Thanks!

like image 301
Kevin Sylvestre Avatar asked May 24 '11 16:05

Kevin Sylvestre


People also ask

Does external CSS override inline?

It even overrides the inline styles from the markup. The only way to override is by using another ! important rule, declared either with higher CSS specificity in the CSS, or equal CSS specificity later in the code.

Which is better inline CSS or external CSS?

The main difference between inline CSS and external CSS is that inline CSS is processed faster as it only requires the browser to download 1 file while using external CSS will require downloading HTML and CSS files separately.

How are external internal and inline style sheets added to Web pages?

CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section. External - by using a <link> element to link to an external CSS file.


2 Answers

Here are couple of gems you can check out:

  • premailer or premailer-rails for rails
  • mail_style
  • premailer plus (fork of the above version)
  • awesome_email
  • roadie

I have no winner at the time writing this answer but premailer seems to be most up-to-date.

like image 94
Lenart Avatar answered Sep 30 '22 09:09

Lenart


Added premailer:

def premailer(message)
  message.text_part.body = Premailer.new(message.text_part.body.to_s, with_html_string: true).to_plain_text
  message.html_part.body = Premailer.new(message.html_part.body.to_s, with_html_string: true).to_inline_css

  return message
end

def welcome(user)
  @user = user

  message = mail ...
end
like image 38
Kevin Sylvestre Avatar answered Sep 30 '22 11:09

Kevin Sylvestre