Files
forwarder/worker/imap_client.py
XikaandPaperclip d8daca15bd feat(backend): add FastAPI, worker, web nginx — full platform (BIT-26121)
- api/: FastAPI app with MySQL (accounts, forwarding_rules, messages)
  - GET/POST/PUT/DELETE /accounts + /accounts/{id}/test
  - GET /messages + /messages/{id}/retry
  - GET /stats
  - POST /connection/test
  - Auto-runs migrations/init.sql on startup
- worker/: Python IMAP poller + BizDocs upload (schedule every 5 min)
- web/: multi-stage Dockerfile — builds admin-ui via Node, serves via nginx
  - nginx proxies /api/ → api:8000, SPA fallback for React Router
- docker-compose.yml: updated web build context + mysql init.sql mount

Co-Authored-By: Paperclip <[email protected]>
2026-06-30 23:04:54 +00:00

113 lines
3.4 KiB
Python

"""IMAP polling — fetch unseen messages with attachments since last UID."""
import imaplib
import email
import logging
from email.header import decode_header
from typing import Iterator
log = logging.getLogger(__name__)
def _decode_str(value) -> str:
if value is None:
return ""
parts = decode_header(value)
out = []
for raw, enc in parts:
if isinstance(raw, bytes):
out.append(raw.decode(enc or "utf-8", errors="replace"))
else:
out.append(raw)
return " ".join(out)
def fetch_new_messages(account: dict) -> Iterator[dict]:
"""
Yield dicts per attachment:
{uid, subject, sender, received_at, filename, data (bytes), size}
"""
host = account["imap_host"]
port = int(account["imap_port"])
ssl = bool(account["imap_ssl"])
user = account["imap_user"]
pw = account["imap_password"]
folder = account.get("folder", "INBOX")
last_uid = int(account["last_uid"])
try:
imap = imaplib.IMAP4_SSL(host, port) if ssl else imaplib.IMAP4(host, port)
except Exception as exc:
log.error("IMAP connect failed for %s: %s", user, exc)
return
try:
imap.login(user, pw)
except Exception as exc:
log.error("IMAP login failed for %s: %s", user, exc)
imap.logout()
return
try:
imap.select(folder, readonly=True)
except Exception as exc:
log.error("IMAP select folder %s failed for %s: %s", folder, user, exc)
imap.logout()
return
try:
typ, data = imap.uid("search", None, f"UID {last_uid + 1}:*")
if typ != "OK" or not data or not data[0]:
return
uid_list = data[0].split()
for uid_bytes in uid_list:
uid = int(uid_bytes)
if uid <= last_uid:
continue
typ2, msg_data = imap.uid("fetch", uid_bytes, "(RFC822)")
if typ2 != "OK" or not msg_data or not msg_data[0]:
continue
raw = msg_data[0][1]
msg = email.message_from_bytes(raw)
subject = _decode_str(msg.get("Subject", ""))
sender = _decode_str(msg.get("From", ""))
date_str = msg.get("Date", "")
from email.utils import parsedate_to_datetime
try:
received_at = parsedate_to_datetime(date_str)
except Exception:
received_at = None
for part in msg.walk():
if part.get_content_maintype() == "multipart":
continue
if part.get("Content-Disposition") is None:
continue
filename = part.get_filename()
if not filename:
continue
filename = _decode_str(filename)
data_bytes = part.get_payload(decode=True)
if not data_bytes:
continue
yield {
"uid": uid,
"subject": subject,
"sender": sender,
"received_at": received_at,
"filename": filename,
"data": data_bytes,
"size": len(data_bytes),
}
finally:
try:
imap.logout()
except Exception:
pass