Skip to content

Receiving Emails with POP3

To receive emails, you use the POP3 protocol, which allows a Mail User Agent (MUA) to download messages from a Mail Delivery Agent (MDA). Python’s poplib module provides a straightforward way to fetch emails via POP3.

Downloading Emails via POP3

Here’s how to connect to a POP3 server and retrieve the latest email:

python
import poplib

email = input('Email: ')
password = input('Password: ')
pop3_server = input('POP3 server: ')

server = poplib.POP3(pop3_server)
server.set_debuglevel(1)
print(server.getwelcome().decode('utf-8'))

server.user(email)
server.pass_(password)

print('Messages: %s. Size: %s' % server.stat())
resp, mails, octets = server.list()
print(mails)

index = len(mails)
resp, lines, octets = server.retr(index)

msg_content = b'\r\n'.join(lines).decode('utf-8')
server.quit()

Parsing the Email

Once you have the raw email content, use the email module to parse it into a readable format:

python
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr

msg = Parser().parsestr(msg_content)

Displaying Email Information

You may want to display the email's details and content. Use a function to print the message structure:

python
def print_info(msg, indent=0):
    for header in ['From', 'To', 'Subject']:
        value = msg.get(header, '')
        if header == 'Subject':
            value = decode_str(value)
        else:
            hdr, addr = parseaddr(value)
            name = decode_str(hdr)
            value = f'{name} <{addr}>'
        print(f'{"  " * indent}{header}: {value}')
    
    if msg.is_multipart():
        parts = msg.get_payload()
        for n, part in enumerate(parts):
            print(f'{"  " * indent}part {n}')
            print(f'{"  " * indent}--------------------')
            print_info(part, indent + 1)
    else:
        content_type = msg.get_content_type()
        if content_type in ['text/plain', 'text/html']:
            content = msg.get_payload(decode=True)
            charset = guess_charset(msg)
            if charset:
                content = content.decode(charset)
            print(f'{"  " * indent}Text: {content}...')
        else:
            print(f'{"  " * indent}Attachment: {content_type}')

Decoding Email Headers

To decode headers properly, use:

python
def decode_str(s):
    value, charset = decode_header(s)[0]
    if charset:
        value = value.decode(charset)
    return value

Guessing Charset

Detect the character set for decoding:

python
def guess_charset(msg):
    charset = msg.get_charset()
    if charset is None:
        content_type = msg.get('Content-Type', '').lower()
        pos = content_type.find('charset=')
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
    return charset

Summary

Using Python's poplib module to receive emails involves connecting to a POP3 server to download the raw email and then parsing it with the email module. This method allows you to present the email content in a readable format.

Receiving Emails with POP3 has loaded