User Tools

Site Tools


Python poplib and email Libraries

In this tutorial I will show you a code snippet which connects to your email host with poplib library and parses the fetched email with email library. As an example I just print the email's subject header. Code is based on Python 2.7. Rest is in the code's comments.
# encoding: utf-8
from __future__ import print_function, unicode_literals
import poplib
import email
import email.header # necessary to decode non-ascii headers
pop_host = "YOUR EMAIL HOST" # IP address or the url of your pop server
pop_username = "" # your pop username
pop_password = "yoursecretpassword" # your pop password
max_print_email = 10 # top 10 emails will be printed
# connect to pop server
pop = poplib.POP3(pop_host)
# get the total number of emails present in server
msgcount = pop.stat()[0] #len(ms.list()[1])
print("msg count=", msgcount)
# print email info from most recent to oldest at most "max_print_email"
for i in range(msgcount, max(0, msgcount - max_print_email), -1):
    response, msg_as_list, size = pop.retr(i) # fetch the email by it's message number
    msg = email.message_from_string('\r\n'.join(msg_as_list)) # creates email object from list of lines
    if "subject" in msg: # if email has a subject header I will print the subject
        # msg behaves like a case insensitive dictionary
        decheader = email.header.decode_header(msg["subject"])
        # decode the header and find the chartset if present, if not charset is None
        subject = decheader[0][0]
        charset = decheader[0][1]
        if charset:
            subject = subject.decode(charset)
        print("msg num=" + str(i), ",", "subject=", subject)

It is up to you to improve this code and read the from, to, cc, bcc headers and body section.


Enter your comment. Wiki syntax is allowed:
python/network/poplib.txt · Last modified: 2015/12/25 13:28 by ozan