imap.py 1.6 KB

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