Skip to content

Instantly share code, notes, and snippets.

@trvsdnn
Created June 26, 2012 02:17
Show Gist options
  • Save trvsdnn/2992801 to your computer and use it in GitHub Desktop.
Save trvsdnn/2992801 to your computer and use it in GitHub Desktop.
extract attachments from a folder of .eml
#! /usr/bin/env ruby
require 'mail'
MAIL_PATH = "#{ARGV.first}/*.eml"
ATTACHMENTS_PATH = File.join(ENV['HOME'], 'found-attachments')
Dir[MAIL_PATH].each do |email|
mail = Mail.read(email)
unless mail.attachments.empty?
mail.attachments.each do |attachment|
filename = attachment.filename
save_path = File.join(ATTACHMENTS_PATH, filename)
if File.exist?(save_path)
filename = Random.rand(1999).to_s + filename
save_path = File.join(ATTACHMENTS_PATH, filename)
end
begin
File.open(new_path, 'w+b', 0644) { |f| f.write attachment.body.decoded }
rescue Exception => e
puts "Unable to save data for #{filename} because #{e.message}"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment