imap.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import os
  2. import re
  3. import logging
  4. from dataclasses import dataclass
  5. from pathlib import Path
  6. from .db import SessionLocal
  7. from .logging_setup import run_cli
  8. from dotenv import load_dotenv
  9. from imap_tools import MailBox
  10. from sqlalchemy import text
  11. load_dotenv()
  12. logger = logging.getLogger(__name__)
  13. @dataclass
  14. class ImapCredentials:
  15. server: str
  16. username: str
  17. password: str
  18. def main():
  19. creds = ImapCredentials(
  20. server=os.getenv("IMAP_SERVER"), username=os.getenv("IMAP_USERNAME"), password=os.getenv("IMAP_PASSWORD")
  21. )
  22. fileserver = Path(os.environ.get("LOCAL_STORAGE"))
  23. with SessionLocal() as db:
  24. q = db.execute(text("SELECT [Client_DB], [Beleg_Nr] FROM [dbo].[Forderungen_Kopf]")).fetchall()
  25. lookup = {row[1]: row[0] for row in q}
  26. with MailBox(creds.server).login(creds.username, creds.password) as mb:
  27. messages = mb.fetch(
  28. mark_seen=True,
  29. bulk=True,
  30. limit=100,
  31. headers_only=False,
  32. reverse=True,
  33. )
  34. for msg in messages:
  35. match = re.findall(r"([WV]\w+\d+)", msg.subject)
  36. if not match:
  37. logger.debug('E-Mail ohne Belegzuordnung übersprungen')
  38. continue
  39. logger.debug('Belegkennung in E-Mail erkannt')
  40. invoice_no = match[0]
  41. if invoice_no not in lookup:
  42. continue
  43. client_db = lookup[invoice_no]
  44. logger.debug('E-Mail einem Beleg zugeordnet')
  45. attachments = {att.filename: att.payload for att in msg.attachments if att.size > 0}
  46. for file, content in attachments.items():
  47. filename: Path = fileserver / client_db / invoice_no / file
  48. filename.parent.mkdir(exist_ok=True, parents=True)
  49. filename.write_bytes(content)
  50. logger.info('Mailanhang abgelegt', extra={'event': 'mail_attachment_saved', 'size_bytes': len(content)})
  51. if __name__ == "__main__":
  52. run_cli(main)