Note: Consider using IMAP with TLS instead of IMAP over SSL. See Minimal Python IMAP over TLS example.
This example code will login to the server using port 993 (IMAP over SSL), list the mailboxes and logout immediately.
#!/usr/bin/env python3 import imaplib server = imaplib.IMAP4_SSL('imap.mydomain.com') server.login('[email protected]', 'password') # Print list of mailboxes on server code, mailboxes = server.list() for mailbox in mailboxes: print(mailbox.decode("utf-8")) # Select mailbox server.select("INBOX") # Cleanup server.close()
Remember to replace:
imap.mydomain.com
with the domain name or IP address of your IMAP server[email protected]
by the email address you want to login withpassword
by the password you want to login with
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 "./imaptest.py", line 5, in <module> server.login('[email protected]', 'mypassword') File "/usr/lib/python3.6/imaplib.py", 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 server.select()
a mailbox first ; this is why we can’t just omit the server.select("INBOX")
line even though we don’t actually do anything with the mailbox. See this post for a more concise example on this behaviour.