Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

POP3 protocol client trong Python (poplib)

Module poplib cung cấp lớp POP3 và POP3_SSL để truy xuất email từ server POP3 (RFC 1939).

Lưu ý: POP3 đã lỗi thời, chất lượng triển khai kém. Nên dùng imaplib.IMAP4 nếu server hỗ trợ IMAP.

Các phương thức chính

Phương thứcMô tả
getwelcome()Chuỗi chào mừng từ server
user(username)Gửi lệnh USER
pass_(password)Gửi mật khẩu (dấu _ tránh từ khóa)
stat()Trạng thái mailbox: (số tin, kích thước)
list()Danh sách tin nhắn: (response, ['msg_num octets', ...], octets)
retr(which)Lấy tin nhắn theo chỉ số, đặt cờ seen
dele(which)Đánh dấu xóa tin nhắn
top(which, howmuch)Lấy header + số dòng body
quit()Đăng xuất, commit thay đổi, đóng kết nối

Ví dụ: Đọc email chưa đọc từ Gmail POP3

import poplib

# POP3_SSL cho Gmail (port 995)
box = poplib.POP3_SSL('pop.googlemail.com', '995')
box.user("YourGmailUserName")
box.pass_('YourPassword')

# Lấy tất cả tin nhắn
num_messages = len(box.list()[1])
for i in range(num_messages):
    for msg_line in box.retr(i + 1)[1]:
        print(msg_line)

box.quit()

Yêu cầu: Bật "Less secure apps" hoặc dùng App Password trong cài đặt Gmail.

POP3 vs POP3_SSL

  • POP3: Kết nối thường (port 110), không mã hóa.
  • POP3_SSL: Kết nối SSL/TLS (port 995), an toàn.

Xử lý lỗi thường gặp

  • poplib.error_proto: Lỗi giao thức (sai user/pass, server từ chối).
  • Timeout: Tăng timeout socket: box = poplib.POP3_SSL(host, port, timeout=30).
  • Encoding: Email thường dùng UTF-8, cần decode: line.decode('utf-8', errors='replace').