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?