Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Integrate 'premailer' with Rails

How does one integrate the 'premailer' gem with a Rails (3.0.7) project? I currently have in my mailer:

def welcome(user)
  @user = user

  mail to: user.email, subject: "Welcome"
end

But I can't figure out how to integrate the library. I need to call:

premailer = Premailer.new(html)
html = premailer.to_inline_css

However, I'm not sure how to access the contents of my email from a mailer action.

like image 651
Stussa Avatar asked May 25 '11 15:05

Stussa


3 Answers

Have a look at the simple premailer-rails gem I recently wrote. It uses Rails mailer hooks to do the conversion.

like image 143
fphilipe Avatar answered Nov 15 '22 01:11

fphilipe


Try:

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 to: user.email, subject: "Welcome"
end
like image 42
Kevin Sylvestre Avatar answered Nov 15 '22 01:11

Kevin Sylvestre


For Rails 4 users you can: add the gems

gem 'premailer-rails'
gem 'nokogiri' (if you don't have it)

add this to your stylesheet (Haml):

%style{type:"text/css"}= Rails.application.assets.find_asset('email_stylesheet').to_s

for some reason it wasn't working with a normal stylesheet_link_tag

That's all I had to do. Hope this help!

like image 5
BezR Avatar answered Nov 15 '22 03:11

BezR