Apple - How to analyze/resolve Gmail timeouts in Apple Mail?

Close Apple Mail and flush your DNS cache - imap.gmail.com is actually a collection of servers and occasionally your DNS will send you a bad one.

In El Capitan the command is sudo dscacheutil -flushcache

It's different for earlier versions.

Even the connection logging in Mail didn't show that DNS was the problem, only that it was a timeout in my case. Unfortunately this is only one possibility.

A way to check is by running the following in Terminal:

$ telnet imap.gmail.com 993
Trying 64.233.187.109...
Connected to gmail-imap.l.google.com.
Escape character is '^]'.

test
FConnection closed by foreign host.

(I typed test there, and the server doesn't understand that so I get disconnected. This proves that the connection between the computer and GMail is fine)