title: Handling connection with imaplib while using context manager
body: <p>I am trying to connect to mail server using python's <code>imaplib</code> . Here is how my code currently stands:</p>
  
  <pre><code>@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()   # &lt;- Check if mailbox is selected
              conn.logout()  # &lt;- Check if logged in
  </code></pre>
  
  <p>How can I check if the user is authenticated and if a mailbox is selected?</p>