Skip to content

Instantly share code, notes, and snippets.

@hwhelchel
Created June 21, 2015 15:11
Show Gist options
  • Save hwhelchel/1b1a5d52b6b56973d8f5 to your computer and use it in GitHub Desktop.
Save hwhelchel/1b1a5d52b6b56973d8f5 to your computer and use it in GitHub Desktop.
Outlook Email Keyword Analysis in Ruby
require 'win32ole'
require 'date'
puts "Please enter keywords you want to match as comma separated values"
keywords = $stdin.gets.chomp.split(",").map(&:strip)
puts "Please enter the Data File. This is case sensitive."
data_file = $stdin.gets.chomp
puts "Please enter the Folders to searched separated by commas. These are also case sensitive."
folders = $stdin.gets.chomp.split(",").map(&:strip)
puts "Please enter the start date in this format YYYY-MM-DD"
start_date = Date.parse($stdin.gets.chomp)
puts "Please enter the end date. (Format YYYY-MM-DD)"
end_date = Date.parse($stdin.gets.chomp)
DATE_RANGE = start_date..end_date
KEYWORDS = /#{keywords.map{|k| Regexp.quote(k) }.join("|")}/i
emails_count = Hash.new(0)
outlook = WIN32OLE.new('Outlook.Application')
mapi = outlook.GetNameSpace('MAPI')
data_file = mapi.Folders(data_file)
filter = "[SentOn] > #{start_date.strftime("%a %D")} 12:00 AM And [SentOn] < #{end_date.strftime("%a %D")} 11:59 PM"
folders.each do |folder|
puts "Analyzing #{folder}"
data_file.Folders(folder).Items.Restrict(filter).each.with_index do |message, index|
if !keywords.empty?
emails_count[message.SentOn.to_date] += 1 if message.body[KEYWORDS] || message.subject[KEYWORDS]
else
emails_count[message.SentOn.to_date] += 1
end
end
end
File.open("email_tracker_output_#{Time.now.to_i}.txt", "w") do |f|
puts "Emails found"
emails_count.each {|date, count|
output = "Date: #{date} Count: #{count}\n"
print output
f.write output
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment