Skip to content

Instantly share code, notes, and snippets.

@pgeraghty
Last active May 2, 2024 12:08
Show Gist options
  • Save pgeraghty/e9b92a99492622c23ac365fd25af4bf7 to your computer and use it in GitHub Desktop.
Save pgeraghty/e9b92a99492622c23ac365fd25af4bf7 to your computer and use it in GitHub Desktop.
Open Outlook email attachments with Ruby
# NB: Attachment#save seems to produce 0 byte files, probably would be resolved via rewind below
require 'mapi/msg'
msg = Mapi::Msg.open '/tmp/email.msg'
# view body
puts msg.properties.body
# save attachments
msg.attachments.each_with_index do |a, idx|
a.data.rewind
filename = File.basename(a.filename || "attachment#{idx}")
File.open(filename, 'wb') { |file| file.write(a.data.read) }
end
# also can be useful
msg_parts = msg.to_mime.parts.find { |part| part.content_type == "multipart/alternative" }.parts
msg_parts.find { |part| part.content_type == "text/plain" }.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment