2.4. POP3

2.4.1. Connection

  • If port is not specified, the standard POP3 port (110)

  • If port is not specified, 995, the standard POP3-over-SSL port is used

2.4.2. poplib API

Table 2.12. poplib API

Method

Arguments

Description

poplib.POP3()

host, port=POP3_PORT, timeout=None

This class implements the actual POP3 protocol

poplib.POP3_SSL()

host, port=POP3_SSL_PORT, keyfile=None, certfile=None, timeout=None, context=None

This is a subclass of POP3 that connects to the server over an SSL encrypted socket

POP3.user()

username

Send user command, response should indicate that a password is required

POP3.pass_()

password

Send password, response includes message count and mailbox size

POP3.apop()

user, secret

Use the more secure APOP authentication to log into the POP3 server

POP3.stat()

Get mailbox status. The result is a tuple of 2 integers: (message count, mailbox size)

POP3.list()

which=None

Request message list, result is in the form (response, ['mesg_num octets', ...], octets)

POP3.retr()

which

Retrieve whole message number which, and set its seen flag. Result is in form (response, ['line', ...], octets)

POP3.dele()

which

Flag message number which for deletion

POP3.rset()

Remove any deletion marks for the mailbox

POP3.quit()

Signoff: commit changes, unlock mailbox, drop connection

POP3.top()

which, howmuch

Retrieves the message header plus howmuch lines of the message after the header of message number which

POP3.utf8()

Try to switch to UTF-8 mode. Returns the server response if successful, raises error_proto if not

POP3.stls()

context=None

Start a TLS session on the active connection as specified in RFC 2595. This is only allowed before user authentication

2.4.3. Retrieve Messages with POP3

Code 2.60. Secured connection to the SMTP server
import poplib


POP3_HOST = 'localhost'
POP3_PORT = 995
POP3_USER = 'myusername'
POP3_PASS = 'mypassword'


server = poplib.POP3_SSL(host=POP3_HOST, port=POP3_PORT, timeout=30)
server.user(POP3_USER)
server.pass_(POP3_PASS)

status, messages, length = server.list()

for message in messages:
    msgid, length = message.split()
    status, content, length = server.retr(int(msgid))
    mail = '\r\n'.join(line.decode() for line in content)

    print(mail)
    print('-' * 30)

"""
Return-Path: <root@ip-172-31-5-83.eu-central-1.compute.internal>
X-Original-To: upload@localhost
Delivered-To: upload@localhost
Received: by ip-172-31-5-83.eu-central-1.compute.internal (Postfix, from userid 0)
	id 2481544BD5; Thu, 23 May 2019 07:36:17 +0000 (UTC)
Subject: test
To: <upload@localhost>
X-Mailer: mail (GNU Mailutils 3.4)
Message-Id: <20190523073617.2481544BD5@ip-172-31-5-83.eu-central-1.compute.internal>
Date: Thu, 23 May 2019 07:36:17 +0000 (UTC)
From: root <root@ip-172-31-5-83.eu-central-1.compute.internal>

hello
------------------------------
"""