Factor out mail management code

Simple refactoring. Not yet ready for prime time.