| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- import os
- import re
- from dataclasses import dataclass
- from pathlib import Path
- from db import get_session
- from dotenv import load_dotenv
- from imap_tools import MailBox
- from sqlalchemy import text
- load_dotenv()
- @dataclass
- class ImapCredentials:
- server: str
- username: str
- password: str
- creds = ImapCredentials(
- server=os.getenv("IMAP_SERVER"), username=os.getenv("IMAP_USERNAME"), password=os.getenv("IMAP_PASSWORD")
- )
- fileserver = Path(os.environ.get("LOCAL_STORAGE"))
- def main():
- db = next(get_session())
- 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:
- print(msg.subject)
- continue
- print(match)
- invoice_no = match[0]
- if invoice_no not in lookup:
- continue
- client_db = lookup[invoice_no]
- print(invoice_no, client_db)
- 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)
- print(filename)
- if __name__ == "__main__":
- main()
|