require 'win32ole' #Connect to outlook ol = WIN32OLE.connect 'outlook.application' #Get inbox inbox = ol.GetNameSpace('MAPI').GetDefaultFolder(6) #Array to hold the matching emails emails = [] print 'Searching: ' total = inbox.items.count #Loop through all messages inbox.items.each.with_index do |msg,idx| print idx if ( msg.Senderemailaddress =~ /@exampledomain.com$/i ) && ( msg.attachments.count > 0 ) && ( msg.attachments.each.any? { |att| att.FileName.end_with?( '.pdf' ) } ) emails << msg end "#{ idx }".length.times { print "\b" } unless idx + 1 == total end puts folder = "#{ ENV['USERPROFILE'] }\\example" Dir.mkdir( folder ) unless Dir.exists?( folder ) index = 0 filenames = [] puts 'Saving: ' emails.each do |msg| special_text = msg.body.scan( /^[a-z]{10}/i )[0] msg.attachments.each do |att| if att.FileName.end_with?( '.pdf' ) filenames << ( filename = "#{ folder }\\#{ special_text }#{ index }#{ att.filename }" ) att.saveasfile filename index += 1 puts filename end end end