CSS Images in Email With Rails 3

大城市里の小女人 提交于 2019-11-30 15:33:12

In response to my other answer, @Kevin wrote:

Thanks for the answer, I did think of doing something like that but I don't think it's possible with the way I have it setup. The mailer call is happening in a after_create call in a model rather than in a controller so I don't think I have access to the request object as you mentioned (or am I mistaken). I do have this in my mailer initializer: ActionMailer::Base.default_url_options[:host] = "localhost:3000" Can I somehow use that hos parameter in my mailer to make it work?

The answer is yes. All rails url-construction helpers should use these defualt_url_options. In addition to setting the :host, you should also force it to use absolute urls by settings this option:

ActionMailer::Base.default_url_options[:only_path] = false

Also, set the asset host like this:

config.action_mailer.asset_host = 'http://localhost:3000'

Then just use the image_path helper instead of hand-writing the url, like this:

<style type="text/css">
body {
    background: url(<%= image_path('mainbg_repeat.jpg') %>) top repeat-x #cfcfcf;
}
</style>

NOTE: Setting default_url_options directly like that is deprecated. Here's the new way to do it:

config.action_mailer.default_url_options = {
    :host => 'localhost:3000',
    :only_path => false
}

Pass your request host as a parameter to the mailer method, and then pass it from the method to the view. So, for example, your mailer method might look like this (example lifted from rails docs and modified here):

class UserMailer < ActionMailer::Base
  default :from => "notifications@example.com"

  def registration_confirmation(user, host)
    @user = user
    @host = host
    mail(:to => user.email, :subject => "Welcome to My Awesome Site")
  end
end

You would call it like this:

def some_action
    UserMailer.registration_confirmation(@user, request.host).deliver
end

Then in your view, you would just use the @host:

<style type="text/css">
body {
    background: url(http://<%= @host %>/images/mainbg_repeat.jpg) top repeat-x #cfcfcf;
}
</style>

This is all assuming the image server is the same as the server running the request. If the image server is hosted elsewhere, you have to output a constant here. You could put something like this in lib/settings.rb:

module Settings
  IMAGE_HOST = 'superawesome.images.com'
end

Then in your view, you'd just output the constant there, like this:

<style type="text/css">
body {
    background: url(http://<%= Settings::IMAGE_HOST %>/images/mainbg_repeat.jpg) top repeat-x #cfcfcf;
}
</style>

If you do not care about performance, the roadie gem can handle urls in the stylesheets for you.

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