Posts Tagged ‘Programming’

IMAP Purge revisited

No Comments »

I noticed, looking at the logs this morning, that the previous script bombs if you delete a mail folder without removing it from your yaml configuration. So, here’s a new and (slightly) improved version

Along with handling the exception, it now creates and appends to a log file per month (instead of creating one each day which proved a bit “messy”).

#!/usr/bin/ruby
require 'net/imap'
require 'date'
require 'yaml'

Config = Struct.new(:imapServer, :userid, :password, :purgePeriods)

root = File.dirname($0) +File::SEPARATOR
t = Date.today
$stderr = $stdout = File.new(root+"cleanup_#{t.year}_#{t.month}.log",'a')
config = YAML.load_file(root+'mailClean.yaml')

imap = Net::IMAP.new(config.imapServer)
imap.login(config.userid,config.password)

puts "================n================"
puts "executing : #{Time.now}"
puts "================n================"
config.purgePeriods.each do |mailbox,days|
  pDate = Date.today - days
  delCount = 0
  puts "====(#{mailbox}:purge before #{pDate})===="
  begin
    imap.select(mailbox)
    msns = imap.search(['NOT','NEW'],'US-ASCII')
    threads = {}
    sl = msns.slice!(0..200)
    while (sl.length>1)
      sl = [sl] if sl.class == 'Fixnum'
      data = imap.fetch(sl,['ENVELOPE'])
      data.each do |d|
        env = d.attr['ENVELOPE']
        next unless env.date
        subject =  env.subject || ''
        threadSubject = subject.sub(/^Re:s*/i,'')
        dt = Date.parse(env.date)
        if threads[threadSubject]
          t = threads[threadSubject]
          t[:latest] = dt if dt > t[:latest]
          t[:msns] << d.seqno
        else
          threads[threadSubject] = {:latest => dt,:msns =>[d.seqno]}
        end
      end
      sl = msns.slice!(0..200)
    end
    threads.each do |key,val|
      if val[:latest] < pDate
        puts "#{key} == #{val[:latest]} #{val[:msns].inspect}n"
        delCount += val[:msns].length
        imap.store(val[:msns],'+FLAGS',[:Deleted])
      end
    end
    puts "deleted #{delCount} messagesn"
    imap.expunge
  rescue
    puts "Error Encountered!:#{$!}"
  end
end

imap.logout

Edit translation
Machine translation (Google):
Loading...
Copy to editor
or Cancel