Python Poplib Module
The poplib module defines a class, POP3, which encapsulates a connection to a POP3 server and implements the protocol as defined in RFC 1939. The POP3 class supports both POP3 and POP3-over-SSL.
Importing the Module
import poplib
Connecting to a Server
Standard Connection
import poplib
# Connect to the POP3 server
# Standard port is 110
pop_server = poplib.POP3('pop.example.com')
# Print the welcome message
print(pop_server.getwelcome().decode('utf-8'))
SSL Connection
For secure connections, use POP3_SSL.
import poplib
# Connect using SSL (default port 995)
pop_server = poplib.POP3_SSL('pop.gmail.com')
Authentication
pop_server.user('your_username')
pop_server.pass_('your_password')
Retrieving Statistics
You can get the number of messages and the total size of the mailbox.
num_messages, total_size = pop_server.stat()
print(f"Messages: {num_messages}, Total Size: {total_size} bytes")
Retrieving Messages
To retrieve a message, use retr(message_number). Note that message numbers start at 1.
if num_messages > 0:
# Retrieve the latest message
# Returns: (response, lines, octets)
resp, lines, octets = pop_server.retr(num_messages)
# Combine lines into a single string
message_content = b'\n'.join(lines).decode('utf-8')
print(message_content)
Quitting
The quit() method signs off, commits changes (like deletions), and closes the connection.
pop_server.quit()