Tuesday, September 29, 2009

Delete all Gmail email


require 'net/imap'

# edit these
user = 'user@gmail.com'
pass = 'password'

# do not edit below this line
result = nil
mboxAll = '[Gmail]/All Mail'
mboxSpam = '[Gmail]/Spam'
mboxTrash = '[Gmail]/Trash'

# connect to the server
imap = Net::IMAP.new('imap.gmail.com', '993', true)
imap.login(user, pass)

# move messages to trash
imap.select(mboxAll)
result = imap.search(["BEFORE", '1-Jan-3000'])
puts "#{result.length} messages found in archives"
if result.length > 0
imap.copy(1..result.length, mboxTrash)
imap.store(1..result.length, "+FLAGS", [:Deleted])
puts "Attempting to move #{result.length} messages to trash..."
imap.expunge
end

# empty spam
imap.select(mboxSpam)
result = imap.search(["BEFORE", '1-Jan-3000'])
puts "#{result.length} messages found in spam"
if result.length > 0
puts "Attempting to delete all #{result.length} messages in spam folder..."
imap.copy(1..result.length, mboxTrash)
imap.store(1..result.length, "+FLAGS", [:Deleted])
imap.expunge
end

# empty trash
imap.select(mboxTrash)
result = imap.search(["BEFORE", '1-Jan-3000'])
puts "#{result.length} messages found in trash"
if result.length > 0
puts "Attempting to delete all #{result.length} messages in trash..."
imap.store(1..result.length, "+FLAGS", [:Deleted])
imap.expunge
end

# end imap session
imap.logout