diff --git a/app.py b/app.py index f098339..12949fc 100644 --- a/app.py +++ b/app.py @@ -1,4 +1,8 @@ -from fastapi import FastAPI, UploadFile, HTTPException, Body +from fastapi import FastAPI, UploadFile, HTTPException, Body, Request +import smtplib +import base64 +from email.message import EmailMessage +import os from PIL import Image import pytesseract from doctr.models import ocr_predictor @@ -27,6 +31,12 @@ file_handler.setFormatter(logging.Formatter( "%(asctime)s - %(levelname)s - %(name)s - %(message)s" )) +SMTP_SERVER = "smtp.gmail.com" +SMTP_PORT = 587 + +EMAIL_ACCOUNT = "faircotbot@gmail.com" +EMAIL_PASSWORD = "zmaqjfrvjpyvcrlg" + import pyodbc def get_db_connection(): @@ -981,4 +991,79 @@ def parse_report(text): # if template not in PARSERS: # return {"template":"UNKNOWN"} # return PARSERS[template].parse(text) - return template \ No newline at end of file + return template + +@app.post("/mail") +async def send_mail(request: Request): + try: + payload = await request.json() + except Exception: + raise HTTPException(status_code=400, detail="Invalid JSON") + + # Champs obligatoires + to = payload.get("to") + subject = payload.get("subject") + body = payload.get("body") + + if not to or not subject or not body: + raise HTTPException( + status_code=400, + detail="Missing required fields: to, subject, body" + ) + + cc = payload.get("cc", []) + attachments = payload.get("attachments", []) + + # Création du message + msg = EmailMessage() + msg["From"] = EMAIL_ACCOUNT + msg["To"] = ", ".join(to) + if cc: + msg["Cc"] = ", ".join(cc) + + msg["Subject"] = subject + msg.set_content(body) + + # Pièces jointes (base64) + for att in attachments: + filename = att.get("filename") + content = att.get("content") + content_type = att.get("content_type", "application/octet-stream") + + if not filename or not content: + raise HTTPException( + status_code=400, + detail="Attachment must contain filename and content" + ) + + try: + file_bytes = base64.b64decode(content) + except Exception: + raise HTTPException( + status_code=400, + detail=f"Invalid base64 for attachment {filename}" + ) + + maintype, subtype = content_type.split("/", 1) + msg.add_attachment( + file_bytes, + maintype=maintype, + subtype=subtype, + filename=filename + ) + + # Envoi SMTP + try: + with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server: + server.starttls() + server.login(EMAIL_ACCOUNT, EMAIL_PASSWORD) + server.send_message(msg) + + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + return { + "status": "sent", + "to": to, + "attachments": len(attachments) + }