import poplib
import ssl
import email
from email.header import decode_header

# SSL兼容修复
try:
    ctx = ssl._create_unverified_context
except:
    ctx = None
if ctx:
    ssl._create_default_https_context = ctx

# ========= 修改这里你的邮箱信息 =========
MAIL_HOST = "pop.163.com"
MAIL_PORT = 995
MAIL_USER = "lyudream@163.com"
MAIL_PWD = "DVZxyF5NKCkR6fL5"

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

if __name__ == "__main__":
    print("=== 开始连接pop.163.com:995 ===")
    try:
        pop = poplib.POP3_SSL(MAIL_HOST, MAIL_PORT)
        print("连接服务器成功，正在登录...")
        pop.user(MAIL_USER)
        pop.pass_(MAIL_PWD)
        print("登录邮箱成功！")

        total, _ = pop.stat()
        print(f"邮箱共有邮件：{total} 封\n")
        if total == 0:
            print("邮箱无邮件")
            pop.quit()
            exit()

        # 从最新邮件遍历
        for i in range(total, 0, -1):
            resp, lines, octet = pop.retr(i)
            msg_raw = b"\r\n".join(lines).decode("utf-8", errors="ignore")
            msg = email.message_from_string(msg_raw)

            subject = decode_text(msg.get("Subject", ""))
            from_addr = msg.get("From", "")

            # 取正文
            body = ""
            if msg.is_multipart():
                for part in msg.walk():
                    t = part.get_content_type()
                    disp = str(part.get("Content-Disposition"))
                    if t == "text/plain" and "attachment" not in disp:
                        payload = part.get_payload(decode=True)
                        body = payload.decode("utf-8", errors="ignore")
                        break
            else:
                payload = msg.get_payload(decode=True)
                body = payload.decode("utf-8", errors="ignore")

            print("========================================")
            print(f"第{i}封邮件")
            print(f"发件人：{from_addr}")
            print(f"标题：{subject}")
            print(f"正文内容：\n{body}")
            print("========================================\n")

        pop.quit()
        print("全部读取完成")

    except Exception as e:
        print("连接/登录失败，错误信息：")
        print(str(e))
