Retrieving Email from a POP3 Server
mServer = poplib.POP3('mail.sfcn.org') mServer.user(getpass.getuser()) mServer.pass_(getpass.getpass()) numMessages = len(mServer.list()[1]) for msg in mServer.retr(mList+1)[1]:
The poplib module included with Python provides simple access to POP3 mail servers that allow you to connect and quickly retrieve messages using your Python scripts.
Connect to the POP3 mail server using the poplib.POP3(host [,port [,keyfile [,certfile]]]) method, where host is the address of the POP3 mail server. The optional port argument defaults to 995. The other optional arguments, keyfile and certfile, refer to the PEM-formatted private key and certificate authentication files, respectively.
To log in to the POP3 server, the code in pop3_mail.py calls the user(username) and pass_(password) methods of the POP3 server object to complete the authentication.
After it's authenticated to the POP3 server, the poplib module provides several methods to manage the mail messages. The example uses the list() method to retrieve a list of messages in the tuple format (response, msglist, size), where response is the server's response code, msglist is a list of messages in string format, and size is the size of the response in bytes.
To retrieve only a single message, use retr(msgid). The retr method returns the message numbered msgid in the form of a tuple (response, lines, size), where response is the server response, lines is a list of strings that compose the mail message, and size is the total size in bytes of the message.
When you are finished managing the mail messages, use the quit() method to close the connection to the POP3 server.
import poplib import getpass mServer = poplib.POP3('mail.sfcn.org') #Login to mail server mServer.user(getpass.getuser()) mServer.pass_(getpass.getpass()) #Get the number of mail messages numMessages = len(mServer.list()[1]) print "You have %d messages." % (numMessages) print "Message List:" #List the subject line of each message for mList in range(numMessages) : for msg in mServer.retr(mList+1)[1]: if msg.startswith('Subject'): print '\t' + msg break mServer.quit()
pop3_mail.py
password: You have 10 messages. Message List: Subject: Static IP Info Subject: IP Address Change Subject: Verizon Wireless Online Statement Subject: New Static IP Address Subject: Your server account has been created Subject: Looking For New Home Projects? Subject: PDF Online - cl_scr_sheet.xls Subject: Professional 11 Upgrade Offer Subject: #1 Ball Played at the U.S. Open Subject: Chapter 3 submission
Output from pop3_mail.py code