contact.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from fastapi import APIRouter, HTTPException, Depends, Form, UploadFile, File
  2. from typing import Optional
  3. import config
  4. from services.email_service import send_contact_form_email
  5. import os
  6. import uuid
  7. router = APIRouter(prefix="/contact", tags=["contact"])
  8. @router.post("")
  9. async def submit_contact_form(
  10. name: str = Form(...),
  11. email: str = Form(...),
  12. subject: str = Form(...),
  13. message: str = Form(...),
  14. file: Optional[UploadFile] = File(None)
  15. ):
  16. """
  17. Handle contact form submission with optional file attachment.
  18. Sends an email notification to the administrator.
  19. """
  20. try:
  21. # For now, we don't save to DB, just send email.
  22. # If we had a contact_messages table, we would INSERT here.
  23. # We could handle the file by saving it or just noting its presence.
  24. # Since send_email currently only supports HTML body without attachments,
  25. # we'll mention the file in the email.
  26. # In a real-world scenario, we'd attach the file to the email.
  27. file_info = ""
  28. if file:
  29. file_info = f"\n<p><strong>Attachment:</strong> {file.filename} ({file.size} bytes)</p>"
  30. # Optional: Save file to a temporary location if needed for manual review
  31. # but for simplified contact form, mentioning it is common.
  32. success = send_contact_form_email(
  33. admin_email=config.SMTP_FROM,
  34. name=name,
  35. from_email=email,
  36. subject=subject,
  37. message=message + file_info
  38. )
  39. if not success:
  40. raise HTTPException(status_code=500, detail="Failed to send message. Please try again later.")
  41. return {"message": "Your message has been sent successfully."}
  42. except Exception as e:
  43. print(f"Contact form error: {e}")
  44. raise HTTPException(status_code=500, detail="Internal server error")