| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import logging
- import os
- import re
- from dataclasses import dataclass
- from pathlib import Path
- from dotenv import load_dotenv
- from imap_tools import MailBox
- from sqlalchemy import text
- from .db import SessionLocal
- from .logging_setup import run_cli
- load_dotenv()
- logger = logging.getLogger(__name__)
- @dataclass
- class ImapCredentials:
- server: str
- username: str
- password: str
- def main():
- creds = ImapCredentials(
- server=os.getenv("IMAP_SERVER"), username=os.getenv("IMAP_USERNAME"), password=os.getenv("IMAP_PASSWORD")
- )
- fileserver = Path(os.environ.get("LOCAL_STORAGE"))
- with SessionLocal() as db:
- q = db.execute(text("SELECT [Client_DB], [Beleg_Nr] FROM [dbo].[Forderungen_Kopf]")).fetchall()
- lookup = {row[1]: row[0] for row in q}
- with MailBox(creds.server).login(creds.username, creds.password) as mb:
- messages = mb.fetch(
- mark_seen=True,
- bulk=True,
- limit=100,
- headers_only=False,
- reverse=True,
- )
- for msg in messages:
- match = re.findall(r"([WV]\w+\d+)", msg.subject)
- if not match:
- logger.debug("E-Mail ohne Belegzuordnung übersprungen")
- continue
- logger.debug("Belegkennung in E-Mail erkannt")
- invoice_no = match[0]
- if invoice_no not in lookup:
- continue
- client_db = lookup[invoice_no]
- logger.debug("E-Mail einem Beleg zugeordnet")
- attachments = {att.filename: att.payload for att in msg.attachments if att.size > 0}
- for file, content in attachments.items():
- filename: Path = fileserver / client_db / invoice_no / file
- filename.parent.mkdir(exist_ok=True, parents=True)
- filename.write_bytes(content)
- logger.info("Mailanhang abgelegt", extra={"event": "mail_attachment_saved", "size_bytes": len(content)})
- if __name__ == "__main__":
- run_cli(main)
|