This can be an infinite loop if the process-status keeps `open' or `run' even though the connection has actually died. In particular, the `imap-wait-for-tag' function can be the cause of the hanging since it sends the LOGOUT command to the dead server and waits for the response. So, I tried modifying it so as to quit in a certain time. The patch to imap.el is below. Anyway, it needs to be reviewed by someone who is skilled in IMAP. The default value of `imap-timeout-seconds' might be too small for slow connections.