Compare commits

...

2 Commits

View File

@@ -105,7 +105,6 @@ def _login_and_prepare(account: EmailAccount, timeout: int = 30):
return conn return conn
@retry()
def fetch_unseen_emails(account: EmailAccount) -> list[Email]: def fetch_unseen_emails(account: EmailAccount) -> list[Email]:
conn = _login_and_prepare(account) conn = _login_and_prepare(account)
@@ -116,20 +115,7 @@ def fetch_unseen_emails(account: EmailAccount) -> list[Email]:
for uid in uids: for uid in uids:
try: try:
# 先查大小,大邮件用 PEEK 避免长时间阻塞导致连接断开被标已读 _, msg_data = conn.uid("FETCH", uid, "RFC822")
_, size_data = conn.uid("FETCH", uid, "(RFC822.SIZE)")
size = 0
if size_data[0]:
m = re.search(rb"RFC822\.SIZE (\d+)", size_data[0])
if m:
size = int(m.group(1))
large = size > 200_000
if large:
logger.info("UID %s 大邮件 (%d bytes),用 PEEK 截断处理", uid, size)
# 大邮件用 PEEK 拉取,不触发服务器标记已读;小邮件正常拉
fetch_cmd = "BODY.PEEK[]" if large else "RFC822"
_, msg_data = conn.uid("FETCH", uid, fetch_cmd)
if msg_data[0] is None: if msg_data[0] is None:
logger.warning("UID %s FETCH 返回空,跳过", uid) logger.warning("UID %s FETCH 返回空,跳过", uid)
continue continue
@@ -147,11 +133,17 @@ def fetch_unseen_emails(account: EmailAccount) -> list[Email]:
logger.info(" 邮件: [%s] from=%s to=%s reply-to=%s (%d 字符)", subject, sender, recipient, reply_to, body_len) logger.info(" 邮件: [%s] from=%s to=%s reply-to=%s (%d 字符)", subject, sender, recipient, reply_to, body_len)
emails.append(Email(uid=uid, subject=subject, sender=sender, recipient=recipient, emails.append(Email(uid=uid, subject=subject, sender=sender, recipient=recipient,
body=body, date=date_str, reply_to=reply_to, account_email=account.username)) body=body, date=date_str, reply_to=reply_to, account_email=account.username))
# FETCH 可能被服务器自动标已读,立即标回未读
conn.uid("STORE", uid, "-FLAGS", "\\Seen")
except Exception as e: except Exception as e:
logger.error("UID %s FETCH 失败,跳过: %s", uid, e) logger.error("UID %s FETCH 失败,跳过: %s", uid, e)
continue continue
conn.logout() try:
conn.logout()
except Exception:
pass
logger.info("共获取 %d 封新邮件", len(emails)) logger.info("共获取 %d 封新邮件", len(emails))
return emails return emails