Rails - ActionMailer - 如何发送您创建的附件?

AnA*_*ice 20 ruby-on-rails ruby-on-rails-3

在rails3和ActionMailer中,我想发送一个.txt文件附件.挑战是这个txt文件不存在,而是我想在给定一大块文本的情况下创建txt文件.

可能?想法?谢谢

Mar*_*uis 53

它描述了ActionMailer :: Base 的API文档中的文件

class ApplicationMailer < ActionMailer::Base
  def welcome(recipient)
    attachments['free_book.pdf'] = File.read('path/to/file.pdf')
    mail(:to => recipient, :subject => "New account information")
  end
end
Run Code Online (Sandbox Code Playgroud)

但这不一定是一个文件,它也可以是一个字符串.所以你可以做类似的事情(我也使用更长的基于哈希的表单,你可以在其中指定自己的mimetype,你可以在ActionMailer :: Base#attachments中找到这方面的文档):

class ApplicationMailer < ActionMailer::Base
  def welcome(recipient)
    attachments['filename.jpg'] = {:mime_type => 'application/mymimetype',
                                   :content => some_string }
    mail(:to => recipient, :subject => "New account information")
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 有些东西给了我关于API的创意,你创建了附件,但从未将它们添加到邮件中...我希望附件至少传递给邮件方法调用... (18认同)
  • @Trejkaz 完全同意。这很奇怪,因为如果你创建一个 `Mail::Message` 对象,你可以向它添加附件:`ActionMailer::Base.mail( from: ..., to: ...).attachments['filename.jpg' ] = some_string` (3认同)