2010-11-24 117 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