mail imporvements

Please rebase on upstream master. This function has some changes since your version was merged.