#!/usr/bin/env python3 """Hand mailed scans to Paperless-ngx. exe.dev delivers mail sent to anything@.exe.xyz into ~/Maildir/new. For each message from an address listed in ~/paperless/mail-senders (one per line), this copies its PDF and image attachments into Paperless's consume folder. Every message, accepted or not, then moves to ~/Maildir/cur, so ~/Maildir/new stays empty. Run by paperless-mail.path / .service. """ import email import email.policy import os import re import sys from email.utils import parseaddr HOME = os.path.expanduser("~") NEW = os.path.join(HOME, "Maildir", "new") CUR = os.path.join(HOME, "Maildir", "cur") CONSUME = os.path.join(HOME, "paperless", "consume") STAGING = os.path.join(HOME, "paperless", "mail-staging") # same disk, outside consume SENDERS = os.path.join(HOME, "paperless", "mail-senders") TYPES = {"application/pdf": "pdf", "image/jpeg": "jpg", "image/png": "png", "image/tiff": "tiff", "image/webp": "webp"} allowed = set() if os.path.exists(SENDERS): with open(SENDERS) as f: allowed = {l.strip().lower() for l in f if l.strip() and not l.startswith("#")} os.makedirs(CUR, exist_ok=True) os.makedirs(STAGING, exist_ok=True) for name in sorted(os.listdir(NEW)): path = os.path.join(NEW, name) with open(path, "rb") as f: msg = email.message_from_binary_file(f, policy=email.policy.default) sender = parseaddr(msg.get("From", ""))[1].lower() saved = 0 if sender in allowed: for part in msg.walk(): if part.is_multipart(): continue ctype = part.get_content_type() filename = part.get_filename() or "" if ctype == "application/octet-stream" and filename.lower().endswith(".pdf"): ctype = "application/pdf" if ctype not in TYPES: continue base = re.sub(r"[^A-Za-z0-9._-]+", "_", os.path.basename(filename)).strip("._") base = base or f"scan.{TYPES[ctype]}" stem, ext = os.path.splitext(base) target, n = base, 1 while os.path.exists(os.path.join(CONSUME, target)): target, n = f"{stem}-{n}{ext}", n + 1 tmp = os.path.join(STAGING, target) with open(tmp, "wb") as out: out.write(part.get_payload(decode=True)) os.rename(tmp, os.path.join(CONSUME, target)) # appears whole saved += 1 print(f"{name}: from {sender}: {saved} attachment(s) to consume") else: print(f"{name}: from {sender or 'unknown'}: not in mail-senders, skipped") os.rename(path, os.path.join(CUR, name + ":2,S")) sys.exit(0)