imap.py 1.7 KB

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