Last active
May 2, 2024 12:08
-
-
Save pgeraghty/e9b92a99492622c23ac365fd25af4bf7 to your computer and use it in GitHub Desktop.
Open Outlook email attachments with Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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