Okay, so I think I managed it. It was more a try and error than pure knowledge, but it works.
Here is what I did:
import imaplib
import socket
class IMAP4(imaplib.IMAP4):
""" Change imaplib to get a timeout """
def __init__(self, host, port, timeout):
# Override first. Open() gets called in Constructor
self.timeout = timeout
imaplib.IMAP4.__init__(self, host, port)
def open(self, host = '', port = imaplib.IMAP4_PORT):
"""Setup connection to remote server on "host:port"
(default: localhost:standard IMAP4 port).
This connection will be used by the routines:
read, readline, send, shutdown.
"""
self.host = host
self.port = port
# New Socket with timeout.
self.sock = socket.create_connection((host, port), self.timeout)
self.file = self.sock.makefile('rb')
def new_stuff():
host = "some-page.com"
port = 143
timeout = 10
try:
imapcon = IMAP4(host, port, timeout)
header = imapcon.welcome
except Exception as e: # Timeout or something else
header = "Something went wrong here: " + str(e)
return header
print new_stuff()
Maybe this is helpful for others