2015-04-12 52 views
1

我可以通過郵件gem通過imap接收電子郵件,並希望將附件添加到我的模型(稱爲消息)中。我獲得基於此blog post了我的代碼,這樣的錯誤:使用Mail Gem和Paperclip解碼附件

Encoding::UndefinedConversionError ("\xC1" from ASCII-8BIT to UTF-8): 

我的代碼:

mail.attachments.each_with_index do | attachment, index | 
     fake_file = AttachmentFile.new("test.jpg") 
     fake_file.write(attachment.decoded) 
     fake_file.flush 
     fake_file.original_filename = attachment.filename 
     fake_file.content_type = "image/gif" 

     @message.doc1 = fake_file if index == 0 and attachment.content_type.start_with?("image/") 
end 

不知道我在做什麼錯誤導致錯誤 - 或許因爲該文件不能讀取二進制模式?另一種選擇是在同一篇文章中給出:

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 

這工作一次與GIF但失敗的PDF提供回滾。另外,我在Windows上開發,這導致了在過去用回形針問題(文件大小不正確讀取等)

該模式具有以下驗證:

validates_attachment_content_type :doc1, :content_type => [ 'application/pdf', /image/ ], :message => "only pdf or img" 

我的日誌文件不是有益的,只有正常輸出第一和第二個選項:

Command :: SET PATH=/usr/bin;%PATH% & file -b --mime "C:/Users/FOUNDA~1/AppData/Local/Temp/c81e728d9d4c2f636f067f89cc14862c20150412-5216-1utzh29.gif" 

不知道什麼樣的初始化存在的郵件寶石 - 它能夠正確地拉動電子郵件。對不起,也許我誤解了你的回覆。

+1

請稍等展開您的問題。一個堆棧跟蹤你得到的錯誤,以及如何'郵件'被初始化將是有用的。 – messanjah

回答

0

我犯了一個錯誤,有一個驗證請求一個特定的文件名結構,這是造成問題。我列出的第二個選項現在完美無瑕。不能說第一個 - 可能會出現相同的問題。