The imaplib module imaplib not provide a way to set a timeout, but you can set a default timeout for new socket connections via socket.setdefaulttimeout :
import socket import imaplib socket.setdefaulttimeout(10) imap = imaplib.IMAP4('test.com', 666)
Or you can also override the imaplib.IMAP4 class with some knowledge from imaplib source and docs, which provides better control:
import imaplib import socket class IMAP(imaplib.IMAP4): def __init__(self, host='', port=imaplib.IMAP4_PORT, timeout=None): self.timeout = timeout
Please note that after creating the connection, we must return the socket timeout back to None in order to switch to blocking mode for the subsequent socket.makefile call, as indicated in the docs method:
... The socket must be in blocking mode (it cannot have a timeout) ....
source share