Minimal Python IMAP over TLS example

Note: Under some circumstances you might want to consider using IMAP over SSL instead. SeeĀ Minimal Python IMAP over SSL example

This example code will login to the server, start a TLS session, list the mailboxes and logout immediately.

#!/usr/bin/env python3
import imaplib
import ssl

# Load system's trusted SSL certificates
tls_context = ssl.create_default_context()

# Connect (unencrypted at first)
server = imaplib.IMAP4('')
# Start TLS encryption. Will fail if TLS session can't be established
# Login. ONLY DO THIS AFTER server.starttls() !!
server.login('', 'password')
# Print list of mailboxes on server
code, mailboxes = server.list()
for mailbox in mailboxes:
# Select mailbox"INBOX")
# Cleanup

Remember to replace:

You need to absolutely ensure that you run server.starttls(...) first and only afterwards do server.login(...). If you fail to do so, eavesdroppers might be able to read your username and password which is not encrypted!

When running this script, a successful output might look like this:

(\HasChildren) "." INBOX
(\HasNoChildren) "." INBOX.Spam
(\HasNoChildren) "." INBOX.Drafts
(\HasNoChildren) "." INBOX.Sent
(\HasNoChildren) "." INBOX.Trash

If your credentials don’t work you’ll see an error message like this:

Traceback (most recent call last):
  File "./", line 5, in <module>
    server.login('', 'mypassword')
  File "/usr/lib/python3.6/", line 598, in login
    raise self.error(dat[-1])
imaplib.error: b'[AUTHENTICATIONFAILED] Authentication failed.'

Note that in order to be able to server.close() the connection, it’s required that you a mailbox first ; this is why we can’t just omit the"INBOX") line even though we don’t actually do anything with the mailbox. See this post for a more concise example on this behaviour.