ikvk / imap_tools

Work with email by IMAP

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Any way to check for connection status?

dzg opened this issue · comments

commented

After some time of being idle, my connection to mailbox disconnects, and I have to login again.

Is there any method to check connection status? If still alive?

Something like mailbox.status ?

Thank you!

IMAP protocol using TCP at transport level, so you should work with socket if you need.

# at imap_tools lib:
mailbox.client.sock

When the s.recv()/send() method returns 0 bytes, it means that the other side has closed or is in the process of closing the connection - the connection is broken

https://docs.python.org/3/library/socket.html

What is your usecase?

commented

Sorry for late reply ... I'm writing a matrix bot to bridge Google Voice. 

I need to check if mailbox connection is still alive before fetching.

Sorry, I don't understand your response above re sock ... what is simplest way to check before getting

imaplib.IMAP4.abort: command: UID => socket error: EOF

?

This is the best I could come up with:

def CheckConnection(mailbox):
    try:
        mailbox.client.sock.getpeercert()
        print('connected')
        return True
    except:
        print('disconnected')
        return False

You have 2 options to work with mailbox:

  1. Connect when you need, get, disconnect.
  2. Connect with idle mode and wait updates, get on update, and then reconnect ones anyway (max 30 min on idle by recomendation).

On net problem you will get exception.

Also you should read about sockets: https://www.google.ru/search?q=how+to+work+socket