【问题标题】:Save a Mail attachment as Active Storage object in Rails在 Rails 中将邮件附件保存为 Active Storage 对象
【发布时间】:2019-08-16 18:56:12
【问题描述】:

我正在使用 Ruby On Rails v.5.2.2、Active Storage 和“邮件”gem。

我正在尝试使用 Active Storage 将电子邮件附件保存到磁盘。

我无法将附件正文直接保存为 IO,也无法将其直接保存到 Tempfile...

【问题讨论】:

    标签: ruby-on-rails email rails-activestorage


    【解决方案1】:

    我找到了一个无需临时保存附件的解决方案。它看起来像这样:

    attachments = mail.attachments.map do |attachment|
      { io: StringIO.new(attachment.decoded), filename: attachment.filename }
    end
    message.files.attach(attachments)
    

    【讨论】:

      【解决方案2】:

      我的解决方案记录在这里:https://where.coraline.codes/blog/processing-email-attachments-with-active-storage/

      代码sn-p:

      def process_attachments
        email.attachments.each do |attachment|
          next unless VALID_MIME_TYPES.include?(attachment.content_type)
          issue.uploads.attach(
            io: attachment.to_io,
            filename: attachment.original_filename,
            content_type: attachment.content_type
          )
        end
      end
      

      对于 MailGun,attachmentActionDispatch::Http::UploadedFile 的一个实例。所以attachment.to_io 是那里的关键。

      【讨论】:

        【解决方案3】:

        这是我采用的解决方案:

        mail = Mail.new(body)
        # ...
        att = mail.attachments.first
        
        temp_file = Tempfile.new('attachment')
        begin
          File.open(temp_file.path, 'wb') do |file|
            file.write(att.body.decoded)
          end
          @msg.files.attach(io: File.open(temp_file.path), filename: att.filename)
        att.filename)
        ensure
           temp_file.close
           temp_file.unlink
        end
        

        【讨论】:

          猜你喜欢
          • 2020-11-04
          • 1970-01-01
          • 1970-01-01
          • 2022-11-11
          • 2018-12-26
          • 2019-09-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多