Performance improvements and SQL changes

As discussed in #162 here are my changes to improve the performance of quickmail.

I was going all the testing on our staging server and not in git, so this is all the changes I have made.

Let me know if you need me to explain certain parts, some of which are a bit hacky and I'm not sure how it will work on different DB engines.

Thanks
Alex