Rails 4,Mailer预览,预览附加图像

我有rails 4.1.6邮件程序预览的问题。

我想在预览模式下看到附加的图像,但它不起作用。 我认为这是不正确的

有我的代码:

邮件文件

class AppMailer < ActionMailer::Base default from: "robot@mysite.com" # AppMailer.test_mail.deliver def test_mail attachments.inline['rails.png'] = File.read(Rails.root.join('app', 'assets', 'images', 'rails.png')) mail( to: 'my-email@gmail.com', subject: "test letter", template_path: "mailers", template_name: "test" ) end end 

预览文件

 class MailerPreview < ActionMailer::Preview def app_mailer AppMailer.test_mail end end 

模板文件

 %p Hello, World! %p= image_tag attachments['rails.png'].url 

当我去

 /rails/mailers/mailer/app_mailer 

我看到预览页面,但图像不起作用。 结果是html代码

 

Hello, World!

所以。 我想,我应该找到一种方法来获取路径/到/文件而不是预览模式下的CID

(当我把信寄到我的邮箱时 – 信看起来不错)

我在预览模式下做错了什么?

对于Rails> = 4.2来预览图像,您应该创建初始化程序:

 # config/initializer/preview_interceptors.rb ActionMailer::Base.register_preview_interceptor(ActionMailer::InlinePreviewInterceptor) 

在Rails邮件预览器得到增强以支持附件查看之前,我正在使用这个(hack-ish)增强function来将Mail::Part#url嵌入到URL本身中。 这样可以在预览器中查看我的内嵌图像(假设我已打开INLINE_MAIL_PART_URLS ),同时在适当的设置中保留原始行为。

 module InlineMailPartUrls def url if ENV["INLINE_MAIL_PART_URLS"] == "true" "data:#{mime_type};base64,#{Base64.encode64(body.decoded)}" else super end end end class Mail::Part prepend InlineMailPartUrls end 

我将此代码保存到config/initializers/inline_mail_part_urls

https://gist.github.com/softcraft-development/2ed70a2a4d6e2c829fac

你没有做错任何事; 这是Rails邮件预览器设计方式的一个缺点。

合理地,Rails Mailer代码生成引用多部分电子邮件中的邮件“部分”的附件的URL。 标记的URL中的“cid”是指特定部分/附件的“内容ID”。 这就是电子邮件中URL的工作方式。

但是,预览器控制器不会在电子邮件客户端的上下文中呈现:它是标准的Web浏览器。 没有“cid”URL协议方案,也没有多部分电子邮件可供参考(它只是标准的HTML文档)。 Rails::MailersController目前还不够聪明,无法实现这一点,只是按原样呈现电子邮件。

为了使其工作,它必须检测对cid: URL的所有引用,并将它们替换为常规http: URL返回自身,然后返回各种附件的内容。

在GitHub / rails上有一个未解决的问题 ,但是到目前为止还没有完成。