使用Rails 3的电子邮件中的CSS图像

时间:2011-09-22 20:18:52

标签: ruby-on-rails actionmailer html-email

我正在尝试发送一封包含Rails 3和Action Mailer的电子邮件。电子邮件很好,但我希望它是HTML格式的一些基本样式,包括背景图像。我知道图像可能会被阻止,直到用户允许它们显示,但我仍然认为最好链接到我的Web服务器上的图像。

名为registration_confirmation.html.erb的电子邮件模板开头如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
    background: url(/images/mainbg_repeat.jpg) top repeat-x #cfcfcf;
    margin: 0px 0px 0px 0px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: #565656;
}

获取背景图片的网址链接以包含完整主机以便背景显示在电子邮件中的最佳方法是什么?

3 个答案:

答案 0 :(得分:16)

在回答我的另一个答案时,@ Kevin写道:

  

感谢您的回答,我确实想过做那样的事情,但我   不要以我设置的方式认为这是可能的。邮件   调用是在模型中的after_create调用中而不是在调用中发生的   控制器,所以我不认为我可以像你一样访问请求对象   提到(或者我错了)。我在我的邮件程序初始化程序中有这个:   ActionMailer :: Base.default_url_options [:host] =“localhost:3000”我可以   以某种方式在我的邮件程序中使用该hos参数使其工作?

答案是肯定的。所有rails url-construction助手都应该使用这些defualt_url_options。除了设置:host之外,您还应该通过设置此选项强制它使用绝对网址:

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

另外,像这样设置资产主机:

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

然后只需使用image_path助手而不是手写网址,如下所示:

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

注意:不推荐直接设置default_url_options。以下是新方法:

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

答案 1 :(得分:2)

将请求主机作为参数传递给邮件程序方法,然后将其从方法传递给视图。因此,例如,您的邮件程序方法可能如下所示(示例从rails docs中提取并在此处进行了修改):

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

你会这样称呼:

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

然后在您看来,您只需使用@host:

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

这是假设图像服务器与运行请求的服务器相同。如果图像服务器托管在其他地方,则必须在此处输出常量。你可以在lib / settings.rb中输入这样的东西:

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

然后在你看来,你只需输出那里的常量,就像这样:

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

答案 2 :(得分:0)

如果您不关心效果,roadie gem可以为您处理样式表中的网址。