Factor out mail management code

Simple refactoring. Ready to go!