代码之家  ›  专栏  ›  技术社区  ›  robotmay

从邮件附件通过回形针或载体上传文件

  •  1
  • robotmay  · 技术社区  · 15 年前

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

    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
    

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

    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
    

    这看起来不管用-有什么建议吗? 结束

    1 回复  |  直到 15 年前
        1
  •  6
  •   DanneManne    15 年前

    我知道,当我试图把邮件附件和回形针一起使用时,我也遇到了一些问题。我记得的问题是,paperclip期望传递给它的文件对象具有某些属性。

    我是这样解决的:

    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)