从 Mail::Part 中提取附件内容

extracting attachment content from Mail::Part

我正在我的 ActionMailer 继承 class 中处理 after_filter 回调,它应该获取外发消息并使用 Paperclip gem 将其附件存储到 AWS。问题是我不知道如何从 Mail::Part 对象中提取文件以便将其传递给 Paperclip。

我原以为这会非常简单,但几个小时的搜索没有找到任何结果。

我没有意识到二进制文件可以表示为字符串。因此,在 Mail::Part 对象上,调用 #decoded(或 #read),使用生成的字符串创建临时文件,然后将该文件分配给使用 Paperclip 的对象。像这样:

Tempfile.open do |temp|
  temp.binmode
  temp << mail_part_obj.read
  temp.flush
  temp.rewind
  uses_pclip << temp
  uses_pclip.save
end