Lots of refactoring :)

Fixes a bug where attachment headers weren't being sent.