| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- import os
- import re
- import logging
- from dataclasses import dataclass
- from pathlib import Path
- from .db import SessionLocal
- from .logging_setup import run_cli
- from dotenv import load_dotenv
- from imap_tools import MailBox
- from sqlalchemy import text
- 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)
|