Save this file with name imaplib_connect.py Write your user id and password in this file
import imaplib import ConfigParser import os def open_connection(verbose=False): # Read the config file config = ConfigParser.ConfigParser() config.read([os.path.expanduser('~/.pymotw')]) # Connect to the server hostname = "imap.mail.microsoftonline.com" if verbose: print 'Connecting to', hostname connection = imaplib.IMAP4_SSL(hostname) # Login to our account username = "XXXXXX@nextag.microsoftonline.com" password = "XXXXXX" if verbose: print 'Logging in as', username connection.login(username, password) return connection if __name__ == '__main__': c = open_connection(verbose=True) try: print c finally: c.logout()