import imaplib import sys from random import choice username = 'youremail@gmail.com' password = 'yourpassword' debug_mode = False def print_shortened_header(fullheader, desired_header_line_names): for headerline in fullheader.split('\n'): isDesiredHeader = False for desired_header_name in desired_header_line_names: if (headerline.find(desired_header_name) == 0): isDesiredHeader = True break if (isDesiredHeader): print headerline def printmailmsg(msgdata): msgparts = msgdata[0][1].split('\r\n\r\n', 1) if len(msgparts) == 2: header = msgparts[0] body = msgparts[1] print_shortened_header(header, ['Date:', 'From:', 'To:', 'Subject:']) print body def printdbg(msg): if debug_mode: print msg try: printdbg("Connecting to server...") server = imaplib.IMAP4_SSL("imap.gmail.com") printdbg("Logging in...") server.login(username, password) printdbg("Selecting mailbox.") server.select('[Gmail]/All Mail') #sent-mail-apr-2000 printdbg("Searching for messages...") typ, msgnums = server.search(None, 'ALL') printdbg(typ) #printdbg(msgnums indexes = msgnums[0].split(); printdbg("Picking a random message from among " + str(len(indexes)) + " messages.") typ, data = server.fetch(choice(indexes), '(RFC822)') printmailmsg(data) # printdbg("Fetching messages..." # for num in msgnums[0].split(): # typ, data = server.fetch(num, '(RFC822)') # printdbg(data # printdbg("Press the any key to continue." # input = raw_input() #server.store(num, '+FLAGS', '\\Seen') printdbg("Closing server connection.") server.close() printdbg("Logging out.") server.logout() except Exception, inst: print "Exception caught: " + str(inst)