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

Kev*_*vin 4 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Ben*_*Lee 16

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

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

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

ActionMailer::Base.default_url_options[:only_path] = false
Run Code Online (Sandbox Code Playgroud)

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

config.action_mailer.asset_host = 'http://localhost:3000'
Run Code Online (Sandbox Code Playgroud)

然后只需使用image_path帮助程序而不是手写url,如下所示:

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

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

config.action_mailer.default_url_options = {
    :host => 'localhost:3000',
    :only_path => false
}
Run Code Online (Sandbox Code Playgroud)