将邮件附件另存为Rails中的Active Storage对象

时间:2019-03-26 11:44:36

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

我正在使用Ruby On Rails v.5.2.2,Active Storage和'mail'gem。

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

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

3 个答案:

答案 0 :(得分:0)

这是我采用的解决方案:

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

答案 1 :(得分:0)

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

代码段:

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是关键。

答案 2 :(得分:0)

我找到了一个解决方案,没有临时保存附件。看起来像这样:

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