Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python's imaplib let you set a timeout?

Tags:

python

imaplib

I'm looking at the API for Python's imaplib.

From what I can tell, there is no way to setup a timeout like you can with smtplib.

Is that correct? How would you handle a host that's invalid if you don't want it to block?

like image 741
okoboko Avatar asked Jun 26 '14 05:06

okoboko


People also ask

What is Imaplib in Python?

Python's client side library called imaplib is used for accessing emails over imap protocol. IMAP stands for Internet Mail Access Protocol. It was first proposed in 1986. Key Points: IMAP allows the client program to manipulate the e-mail message on the server without downloading them on the local computer.

How do I install Imaplib?

The imaplib module is a pre-installed library of Python that comes with the Python installation packages, and that's why we don't have to do any installation process for installing this library.


2 Answers

The imaplib module doesn't provide a way to set timeout, but you can set a default timeout for new socket connections via the socket.setdefaulttimeout:

import socket
import imaplib
socket.setdefaulttimeout(10)
imap = imaplib.IMAP4('test.com', 666)

Or you can also go about overriding 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
        # no super(), it's an old-style class
        imaplib.IMAP4.__init__(self, host, port)

    def open(self, host='', port=imaplib.IMAP4_PORT):
        self.host = host
        self.port = port
        self.sock = socket.create_connection((host, port), timeout=self.timeout)
        # clear timeout for socket.makefile, needs blocking mode
        self.sock.settimeout(None)
        self.file = self.sock.makefile('rb')

Note that after creating the connection we should set the socket timeout back to None to get it to blocking mode for subsequent socket.makefile call, as stated in the method docs:

... The socket must be in blocking mode (it can not have a timeout). ...

like image 169
famousgarkin Avatar answered Sep 18 '22 15:09

famousgarkin


import imaplib
...
# ssl and timeout are config values
# connection to IMAP server
if ssl:
    imapResource = imaplib.IMAP4_SSL(server, port)
else:
    imapResource = imaplib.IMAP4(server, port)
# communications timeout
sock=imapResource.socket()
timeout = 60 * 5 # 5 minutes
sock.settimeout(timeout)
like image 45
Serge Tahé Avatar answered Sep 20 '22 15:09

Serge Tahé