## open connection to mail server (Secured using SSL) myEmailConnection = poplib.POP3_SSL(mailServer) ## print the response message from server print myEmailConnection.getwelcome() ## set email address myEmailConnection.user(emailID) ## set password myEmailConnection.pass_(emailPass) ## get information about the email address EmailInformation = myEmailConnection.stat() print "Number of new emails: %s (%s bytes)"% EmailInformation ## Reading an email print "\n\n===\nRead messages\n===\n\n" ## Read all emails numberofmails = EmailInformation for i in range(numberOfMails): for email in myEmailConnection.retr(i+1): print email
You may noticed that we first opened a connection to POP3 (Post Office Protocol version 3) server then we using the user email ID/Password to retrieve email information and content. You have to notice that we sent the password using secured channel(SSL). The gmail service allow you to change the date that you want to start reading your message from, just go to your email options. There are other functions that we didn't use in this code snippet for example :
myEmailConnection.retr(index) ( used in the snippet) Retrieve whole message number index myEmailConnection.dele(index) Flag message number index for deletion. myEmailConnection.quit() Sign-off: unlock mailbox after committing changes, close connection.
You can also read email using IMAP, IMAP has more features than POP, for example using IMAP you can create folders, move/delete/send messages. Following snippet present an example for using a built in package "imaplib".
## create a new folder status, createFolder_response = imap.create('myFolders.xyz')
## folders list status, folder_list = imap.list()
## list sub-folders status, sub_folder_list = imap.list(directory='insd')
## select a specific folder status, data = imap.select('INBOX')
## searching current folder using title keywords status, messages = imap.search(None,'(SUBJECT "Work Report")') ## fetching message header by using message( ID) status, msg_header = imap.fetch('1','(BODY.PEEK[HEADER])')
## fetching the full message ( ID=1) status, AllTheMessage= imap.fetch('1','(RFC822)')