【发布时间】: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
我正在使用 Ruby On Rails v.5.2.2、Active Storage 和“邮件”gem。
我正在尝试使用 Active Storage 将电子邮件附件保存到磁盘。
我无法将附件正文直接保存为 IO,也无法将其直接保存到 Tempfile...
【问题讨论】:
标签: ruby-on-rails email rails-activestorage
我找到了一个无需临时保存附件的解决方案。它看起来像这样:
attachments = mail.attachments.map do |attachment|
{ io: StringIO.new(attachment.decoded), filename: attachment.filename }
end
message.files.attach(attachments)
【讨论】:
我的解决方案记录在这里: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,attachment 是 ActionDispatch::Http::UploadedFile 的一个实例。所以attachment.to_io 是那里的关键。
【讨论】:
这是我采用的解决方案:
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
【讨论】: