Converting External CSS to Inline CSS for Mail in Rails

萝らか妹 提交于 2019-12-03 04:25:15

问题


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!


回答1:


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.




回答2:


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



回答3:


There's just one problem with your reasoning.....many styles, even inline, aren't supported.

Here's a reference for what is supported in email

In your example, you use the display: tag, which isn't supported by Outlook 07+

My company sends out thousands of emails a day and I often have a hand in building them. In practice, inline styles work, but it's not as simple as just in-lining everything and it will work. You have to be extremely careful about what you use and how you use it. I've resorted to my beginnings, doing nearly everything in pure HTML with tables for layouts. It's basically the only way I've found to get things to work nearly 100% of the time.

If you're building this functionality into an app that's going to get a lot of use, I'd also strongly recommend building in Email on Acid via their API. While you can code a very good quality output, Microsoft will no doubt find some way to make your valid code not work. Email on Acid will render using whatever madness Microsoft is using at the time to show you if your email works. It's pure genius and required use for those who are serious about sending a ton of emails. And no, I don't work for the company....



来源:https://stackoverflow.com/questions/6113622/converting-external-css-to-inline-css-for-mail-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!