通过Paperclip或Carrierwave从Mail附件上载文件

rob*_*may 1 ruby email file-upload ruby-on-rails

如果我有邮件对象,例如:

mail = Mail.new do
  from      "jim@gmail.com"
  to        "jane@yahoo.com"
  subject   "Example"
  text_part do
    body    "Blarg"
  end
  add_file  "/some/file/or/some_such.jpg"
end
Run Code Online (Sandbox Code Playgroud)

如果我在我的申请中收到上述邮件

received_mail = mail.encoded
Message.parse(received_mail)
Run Code Online (Sandbox Code Playgroud)

我如何将附件传递给CarrierWave/Paperclip(没有讨论哪个,我会使用哪一个处理这个最好)?我尝试了几种不同的方法,但是我一直在遇到各种绊脚石 - 有没有人有一个可行的解决方案呢?

我目前的尝试是:

mail.attachments.each do |attachment|
  self.attachments << Attachment.new(:file => Tempfile.new(attachment.filename) {|f| f.write(attachment.decoded)})
end
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用 - 任何提示?结束

Dan*_*nne 6

我知道当我尝试接收邮件附件并将其与回形针一起使用时,我也遇到了一些问题.我记得的问题是,paperclip期望传递给它的File对象上的某些属性.

我这样解决了:

mail.attachments.each do |attachment|
  file = StringIO.new(attachment.decoded)
  file.class.class_eval { attr_accessor :original_filename, :content_type }
  file.original_filename = attachment.filename
  file.content_type = attachment.mime_type

  #Then you attach it where you want it
  self.attachments << Attachment.new(:file => file)
Run Code Online (Sandbox Code Playgroud)