- auth.py: DKIM potpis provjeravamo sami (dkimpy + DNS), ne vjerujemo zaglavljima; potpis mora biti od domene iz From, pokrivati from/to/date - idriz@kbr4.dev mora biti u To/Cc, Date najviše 3 dana star, Message-ID samo jednom (zaštita od ponovnog slanja starih potpisanih mailova) - privremeni DNS kvar: poruka se vraća u nepročitane i provjerava ponovo - admin /email: zadnjih 20 odbijenih poruka sa razlogom - requirements: dkimpy Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
191 lines
7.2 KiB
Python
191 lines
7.2 KiB
Python
"""IMAP (prijem) i SMTP (slanje) za email kanal. Sinhrono — kanal ga zove kroz asyncio.to_thread.
|
|
|
|
Server i kredencijali: IDRIZ_MAIL_HOST (mail.kbr4.dev), IDRIZ_MAIL_CREDENTIALS
|
|
(~/.mailcredentials, format "email:lozinka").
|
|
"""
|
|
import email
|
|
import email.policy
|
|
import html
|
|
import imaplib
|
|
import logging
|
|
import mimetypes
|
|
import os
|
|
import re
|
|
import smtplib
|
|
import ssl
|
|
from dataclasses import dataclass, field
|
|
from email.message import EmailMessage
|
|
from email.utils import getaddresses, make_msgid, formatdate
|
|
from pathlib import Path
|
|
|
|
log = logging.getLogger("idriz.email")
|
|
|
|
HOST = os.environ.get("IDRIZ_MAIL_HOST", "mail.kbr4.dev")
|
|
CREDENTIALS = Path(os.environ.get("IDRIZ_MAIL_CREDENTIALS", str(Path.home() / ".mailcredentials")))
|
|
IMAP_PORT = 993
|
|
SMTP_PORT = 465
|
|
|
|
|
|
def credentials() -> tuple[str, str]:
|
|
user, pw = CREDENTIALS.read_text(encoding="utf-8").strip().split(":", 1)
|
|
return user.strip(), pw.strip()
|
|
|
|
|
|
@dataclass
|
|
class Dolazna:
|
|
uid: str
|
|
od: str # adresa pošiljaoca (mala slova)
|
|
od_ime: str
|
|
naslov: str
|
|
tekst: str # tijelo bez citiranog dijela
|
|
message_id: str
|
|
references: list[str]
|
|
auto: bool # automatska poruka (auto-reply, bulk...) — ne odgovaramo
|
|
auth: str = "odbij" # rezultat auth.provjeri: "ok" | "odbij" | "privremeno"
|
|
auth_razlog: str = ""
|
|
prilozi: list[str] = field(default_factory=list) # imena priloga (zasad se ne obrađuju)
|
|
|
|
@property
|
|
def thread_key(self) -> str:
|
|
"""Korijen niti: prvi Message-ID iz References, inače vlastiti."""
|
|
return self.references[0] if self.references else self.message_id
|
|
|
|
|
|
# ---------- parsiranje ----------
|
|
_QUOTE_HEAD = re.compile(
|
|
r"^(On .+wrote:|Dana .+(napisao|napisala|je napisao|je napisala).*:|.+ (je napisao|je napisala|wrote):"
|
|
r"|-----\s*Original Message\s*-----|From: .+)\s*$", re.IGNORECASE)
|
|
|
|
|
|
def _strip_quote(text: str) -> str:
|
|
out = []
|
|
for line in text.splitlines():
|
|
if _QUOTE_HEAD.match(line.strip()):
|
|
break
|
|
if line.startswith(">"):
|
|
continue
|
|
out.append(line)
|
|
return "\n".join(out).strip()
|
|
|
|
|
|
def _html_to_text(s: str) -> str:
|
|
s = re.sub(r"(?is)<(script|style|blockquote).*?</\1>", "", s)
|
|
s = re.sub(r"(?i)<br\s*/?>|</p>|</div>", "\n", s)
|
|
s = re.sub(r"<[^>]+>", "", s)
|
|
return html.unescape(s)
|
|
|
|
|
|
def _body(msg) -> tuple[str, list[str]]:
|
|
plain, htm, prilozi = "", "", []
|
|
for part in msg.walk():
|
|
if part.is_multipart():
|
|
continue
|
|
disp = part.get_content_disposition()
|
|
if disp == "attachment" or (disp == "inline" and part.get_filename()):
|
|
prilozi.append(part.get_filename() or "prilog")
|
|
continue
|
|
ctype = part.get_content_type()
|
|
try:
|
|
content = part.get_content()
|
|
except (LookupError, KeyError):
|
|
content = part.get_payload(decode=True).decode("utf-8", errors="replace")
|
|
if ctype == "text/plain" and not plain:
|
|
plain = content
|
|
elif ctype == "text/html" and not htm:
|
|
htm = content
|
|
text = plain or _html_to_text(htm)
|
|
return _strip_quote(text), prilozi
|
|
|
|
|
|
def parse(uid: str, raw: bytes, own: str = "") -> Dolazna:
|
|
"""`own` = naša adresa; bez nje se autentičnost ne provjerava (auth="odbij")."""
|
|
from . import auth # lijeno: dkim/dns treba samo asistentu, ne adminu
|
|
msg = email.message_from_bytes(raw, policy=email.policy.default)
|
|
status, razlog = auth.provjeri(raw, msg, own) if own else ("odbij", "nije provjereno")
|
|
(ime, adresa), = getaddresses([str(msg.get("From", ""))]) or [("", "")]
|
|
refs = re.findall(r"<[^>]+>", str(msg.get("References", "")))
|
|
irt = re.findall(r"<[^>]+>", str(msg.get("In-Reply-To", "")))
|
|
if not refs and irt:
|
|
refs = irt
|
|
auto = (str(msg.get("Auto-Submitted", "no")).lower() != "no"
|
|
or str(msg.get("Precedence", "")).lower() in ("bulk", "list", "junk")
|
|
or bool(msg.get("List-Id")))
|
|
tekst, prilozi = _body(msg)
|
|
return Dolazna(
|
|
uid=uid, od=adresa.strip().lower(), od_ime=ime, naslov=str(msg.get("Subject", "")).strip(),
|
|
tekst=tekst, message_id=str(msg.get("Message-ID", "")).strip() or make_msgid(),
|
|
references=refs, auto=auto, auth=status, auth_razlog=razlog, prilozi=prilozi)
|
|
|
|
|
|
# ---------- IMAP ----------
|
|
def fetch_unseen() -> list[Dolazna]:
|
|
"""Pokupi nepročitane poruke iz INBOX-a i označi ih kao pročitane.
|
|
|
|
Autentičnost se provjerava ovdje (DKIM preko DNS-a). Ako DNS privremeno ne radi,
|
|
poruka se vraća u nepročitane da se provjeri pri sljedećoj provjeri pošte.
|
|
"""
|
|
user, pw = credentials()
|
|
out = []
|
|
with imaplib.IMAP4_SSL(HOST, IMAP_PORT, ssl_context=ssl.create_default_context()) as imap:
|
|
imap.login(user, pw)
|
|
imap.select("INBOX")
|
|
typ, data = imap.uid("SEARCH", None, "UNSEEN")
|
|
uids = data[0].split() if typ == "OK" and data and data[0] else []
|
|
for uid in uids:
|
|
typ, msgdata = imap.uid("FETCH", uid, "(BODY.PEEK[])")
|
|
if typ != "OK" or not msgdata or not isinstance(msgdata[0], tuple):
|
|
continue
|
|
imap.uid("STORE", uid, "+FLAGS", "(\\Seen)")
|
|
try:
|
|
d = parse(uid.decode(), msgdata[0][1], own=user)
|
|
except Exception: # noqa: BLE001
|
|
log.exception("ne mogu parsirati poruku uid=%s", uid)
|
|
continue
|
|
if d.auth == "privremeno":
|
|
log.warning("uid=%s: %s — pokušaću ponovo", uid, d.auth_razlog)
|
|
imap.uid("STORE", uid, "-FLAGS", "(\\Seen)")
|
|
continue
|
|
out.append(d)
|
|
imap.logout()
|
|
return out
|
|
|
|
|
|
# ---------- SMTP ----------
|
|
def build_reply(dolazna: Dolazna, tekst: str, prilozi: list[Path], own_msgid: str) -> EmailMessage:
|
|
user, _ = credentials()
|
|
msg = EmailMessage()
|
|
msg["From"] = f"Idriz <{user}>"
|
|
msg["To"] = dolazna.od
|
|
naslov = dolazna.naslov or "Idriz"
|
|
msg["Subject"] = naslov if naslov.lower().startswith(("re:", "odg:")) else f"Re: {naslov}"
|
|
msg["Date"] = formatdate(localtime=True)
|
|
msg["Message-ID"] = own_msgid
|
|
msg["In-Reply-To"] = dolazna.message_id
|
|
msg["References"] = " ".join(dolazna.references + [dolazna.message_id])
|
|
msg["Auto-Submitted"] = "auto-replied" # da drugi automati ne odgovaraju nama
|
|
msg.set_content(tekst)
|
|
for p in prilozi:
|
|
ctype, _ = mimetypes.guess_type(p.name)
|
|
maintype, subtype = (ctype or "application/octet-stream").split("/", 1)
|
|
msg.add_attachment(p.read_bytes(), maintype=maintype, subtype=subtype, filename=p.name)
|
|
return msg
|
|
|
|
|
|
def send(msg: EmailMessage) -> None:
|
|
user, pw = credentials()
|
|
with smtplib.SMTP_SSL(HOST, SMTP_PORT, context=ssl.create_default_context(), timeout=60) as smtp:
|
|
smtp.login(user, pw)
|
|
smtp.send_message(msg)
|
|
# kopija u "Sent" (nije kritično ako ne uspije)
|
|
try:
|
|
with imaplib.IMAP4_SSL(HOST, IMAP_PORT, ssl_context=ssl.create_default_context()) as imap:
|
|
imap.login(user, pw)
|
|
imap.append("Sent", "(\\Seen)", None, msg.as_bytes())
|
|
imap.logout()
|
|
except Exception: # noqa: BLE001
|
|
log.warning("nisam spremio kopiju u Sent", exc_info=True)
|
|
|
|
|
|
def new_msgid() -> str:
|
|
return make_msgid(domain=credentials()[0].split("@", 1)[1])
|