In this tutorial you will learn how to receive email using the poplib module. The mail server needs to support pop3, but most mail servers do this. The Post Office Protocol (POP3) is for receiving mail only, for sending you will need the SMTP protocol.
Every email will contain many variables, but these are the most important ones:
where did the email come from?
where was the email sent to?
Reading Email Example
You can request messages directly from a mail server using the Post Office Protocol (protocol). You do not have to worry about the internal protocol because you can use the poplib module. Connect and authenticate with the server using:
# connect to server server = poplib.POP3(SERVER)
# login server.user(USER) server.pass_(PASSWORD)
The program below gets 10 emails from the server including mail header
import poplib import string, random import StringIO, rfc822
defreadMail(): SERVER = "YOUR MAIL SERVER" USER = "YOUR USERNAME [email protected]" PASSWORD = "YOUR PASSWORD" # connect to server server = poplib.POP3(SERVER) # login server.user(USER) server.pass_(PASSWORD) # list items on server resp, items, octets = server.list() for i inrange(0,10): id, size = string.split(items[i]) resp, text, octets = server.retr(id) text = string.join(text, "\n") file = StringIO.StringIO(text) message = rfc822.Message(file) for k, v in message.items(): print k, "=", v