Simple IMAP Account Verification in Python

November 22nd, 2014

imaplib is a great library for handling IMAP communication. It supports both plaintext IMAP and IMAP over SSL (IMAPS) with ease. Connecting to an IMAP server is achieved as follows:

import imaplib

host = "mx.sasdataservices.com"
port = 143
ssl = 0

try:
	if ssl:
		imap = imaplib.IMAP4_SSL(host, port)
	else:
		imap = imaplib.IMAP4(host, port)
	welcomeMsg = imap.welcome
	print "IMAP Banner: %s" %(welcomeMsg)
except:
	print "Connection Failed"
	quit()

This results in the following output: “IMAP Banner: * OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA IDLE ACL ACL2=UNION STARTTLS] Courier-IMAP ready. Copyright 1998-2011 Double Precision, Inc. See COPYING for distribution information.” Now, to log in:

username="user@email.com"
password="password"

try:
	loginMsg = imap.login(username, password)
	print "Login Message: %s" %(loginMsg[1])
except:
	print "Login Failed"
	quit()

With acceptable credentials, the response is: “Login Message: [‘LOGIN Ok.’]”. Lastly, to print a list of all mailboxes in the account:

try:
	mBoxes = imap.list()
	for mBox in mBoxes[1]:
		print mBox
except:
	print "Couldn't get Mail Boxes"
quit()

Read the rest of this entry »