Multiple fixed of various problems after testing on 50000 production emails

I fixed several exceptions after testing on a huge email database. Unit tests are also provided.

Thank you.