2010-11-24 67 views
1

如果我有一个邮件对象,如:从邮件附件上传通过回形针或Carrierwave文件

mail = Mail.new do 
    from  "[email protected]" 
    to  "[email protected]" 
    subject "Example" 
    text_part do 
    body "Blarg" 
    end 
    add_file "/some/file/or/some_such.jpg" 
end 

如果我收到上述邮件在我的应用

received_mail = mail.encoded 
Message.parse(received_mail) 

会如何我将附件传递给CarrierWave/Paperclip(不会因为哪一个最擅长处理这个问题而烦恼)?我已经尝试了几种不同的方法,但我一直跑到各种绊脚石 - 有没有人得到一个工作解决方案?

我现在的尝试是:

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

这似乎并没有工作 - 任何提示? 结束

回答

6

我知道,当我试图拿回邮件附件并用回形针使用它们时,我也遇到了一些问题。我记得这个问题是回形针期望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) 
+0

真棒,这完美地工作。我以前曾尝试过使用StringIO对象,但是我摔倒了额外的属性 - 从未想过将它们设置为attr_accessors。非常感谢你 :) – robotmay 2010-11-25 08:02:34