Skip to content

Instantly share code, notes, and snippets.

@maxandersen
Created July 9, 2015 06:44
Show Gist options
  • Save maxandersen/12ed6aaa5b97471b469f to your computer and use it in GitHub Desktop.
Save maxandersen/12ed6aaa5b97471b469f to your computer and use it in GitHub Desktop.
lua script for imapfilter that deletes empty mailboxes
--- Removes mailboxes with no messages and no subfolders.
--- Will keep iterating over folders with subfolders until it
--- cannot find anymore candidates to delete
--- called by running: `removeEmptyMailboxes(account, 'INBOX', '*')`
function removeEmptyMailboxes(account, base, pattern)
candidates = account:list_all(base,pattern)
while(#candidates > 0) do
print ("Start scanning " .. #candidates .. " boxes to see if empty...")
candidates = removeMailboxes(account, candidates)
end
end
function removeMailboxes(account, boxes)
candidates = {} -- folders we could not delete because it had sub folders
deleted = 0
for _,box in pairs(boxes) do
exist, unread, unseen, uidnext = account[box]:check_status()
if(exist==0) then
subboxes = account:list_all(box, '*')
if (# subboxes > 0) then
print ("Can't delete " .. box .. " because it has " .. # subboxes .. " folders")
table.insert(candidates, box)
else
print ("Want to delete " .. box)
account:delete_mailbox(box)
deleted = deleted + 1
end
end
end
if(deleted>0) then
return candidates
else
print ("Could not delete any mailboxes thus no more candidates to delete.")
return {}
end
end
@maluramichael
Copy link

Thank you. Had to call it like this removeEmptyMailboxes(account, '', '*')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment