Mail code should be refactored to be easier to comprehend
When reviewing !2598 (merged), it became clear that the code for processing emails is not really easy to read and understand. We should refactor it and break up big functions into smaller ones.