Thursday, September 24, 2009

Ruby Gmail E-Mail Delete Script


#!/usr/bin/ruby

require 'net/imap'

$result = nil
$count = 0
$maxthreads = 8
$threadcount = 0
$user = ''
$pass = ''

def probeServer
imap = Net::IMAP.new('imap.gmail.com', '993', true)
imap.login($user, $pass)
imap.select('[Gmail]/All Mail')
$result = imap.search(["BEFORE", "1-Jan-2009"])
puts "#{$result.length} messages found"
imap.logout
imap.disconnect

rescue Net::IMAP::NoResponseError => e
# discard
rescue Net::IMAP::ByeResponseError => e
# discard
rescue => e
puts e
end

def deleteMsgs(start, stop)
$threadcount = $threadcount + 1
puts "started thead #{$threadcount} of #{$maxthreads}"

imap = Net::IMAP.new('imap.gmail.com', '993', true)
imap.login($user, $pass)
imap.select('[Gmail]/All Mail')

#result.each do |id|
start.upto(stop) { |id|
imap.copy(id, '[Gmail]/Trash')
imap.store(id, "+FLAGS", [:Deleted])
$count = $count + 1
}
imap.expunge
imap.logout
imap.disconnect

rescue Net::IMAP::NoResponseError => e
# discard
rescue Net::IMAP::ByeResponseError => e
# discard
rescue => e
puts e

puts "moved #{$count} messages to trash"
end

def statusThread
while($count < $result.size)
puts "pimped out #{$count} of #{$result.size} messages"
sleep(1)
end
end


if(ARGV.size == 2)
$user = ARGV[0]
$pass = ARGV[1]
else
puts "Usage: ruby g.rb "
exit
end

puts "Started at #{Time.now}"

probeServer
msgsPerThread = ($result.size / $maxthreads).ceil

st = Thread.new { statusThread() }
t = Array.new($maxthreads)
for i in (1..$maxthreads)
if i == 1
start = 1
else
start = i * msgsPerThread
end
stop = start + msgsPerThread

t[i] = Thread.new { deleteMsgs(start, stop) }
end
for i in (1..$maxthreads)
t[i].join # rescue nil
end


puts "Ended at #{Time.now}"