Wrapper functions for read/write, change while

Added some wrapper functions from the git source code that make read/write a bit
more intelligent in terms of handling errors.

Added a sleep to ensure the email has completely arrived on the server before
commencing any work.

Also reverted the while condition to a check for a read of 0. The BUF_SIZE
comparison worked 99% of the time, but occasionally failed likely due to
multibyte characters or some other edge case. This would cause the email to be
truncated and data in the attachments to be lost.