Quantcast
Channel: Active questions tagged email - Stack Overflow
Viewing all articles
Browse latest Browse all 29762

Handling connection with imaplib while using context manager

$
0
0

I am trying to connect to mail server using python's imaplib . Here is how my code currently stands:

@contextlib.contextmanager
def get_connection(username: str, password: str, host=GMAIL_IMAP_HOST, port=GMAIL_IMAP_PORT):
    '''
    ARGS:
        username: User username
        password: User Password
        host: IMAP server address
        post: IMAP port

    Connect to IMAP server and close connection
    '''

    conn = None

    try:
        conn = imaplib.IMAP4_SSL(host, port)
        conn.login(username, password)
        response, _ = conn.select('INBOX')

        if response != 'OK':
            raise MyException('An error occurred authenticating - {}'.format(response))

        yield conn
    finally:
        if conn is not None:
            conn.close()   # <- Check if mailbox is selected
            conn.logout()  # <- Check if logged in

How can I check if the user is authenticated and if a mailbox is selected?


Viewing all articles
Browse latest Browse all 29762

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>