| from fastapi import FastAPI, HTTPException |
| import smtplib |
| from dotenv import load_dotenv |
| import os |
| from pydantic import BaseModel |
| from fastapi.middleware.cors import CORSMiddleware |
| import ssl |
| import uvicorn |
|
|
| |
| load_dotenv() |
| sender_email = os.getenv('sender_email') |
| receiver_email = os.getenv('receiver_email') |
| app_password = os.getenv("app_password") |
|
|
| class message_info(BaseModel): |
| name: str |
| message: str |
| email: str |
|
|
| app = FastAPI() |
|
|
| app.add_middleware( |
| CORSMiddleware, |
| allow_origins=["*"], |
| allow_credentials=True, |
| allow_methods=["*"], |
| allow_headers=["*"], |
| ) |
|
|
| @app.get("/") |
| def read_root(): |
| return {"message": "Server is running"} |
|
|
| @app.post('/portfolio_message') |
| def postfolio(m: message_info): |
| """ |
| Handles a message sent from the portfolio contact form. |
| This function now creates and closes the SMTP connection for each request, |
| making the application more robust against connection errors at startup. |
| """ |
| if not all([sender_email, receiver_email, app_password]): |
| raise HTTPException(status_code=500, detail="Missing environment variables.") |
|
|
| subject = "Portfolio Message" |
| body = f"Name: {m.name}\nEmail: {m.email}\n\nMessage:\n{m.message}" |
| message = f"Subject: {subject}\n\n{body}" |
|
|
| try: |
| |
| context = ssl.create_default_context() |
| with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: |
| server.login(sender_email, app_password) |
| server.sendmail(sender_email, receiver_email, message) |
| except smtplib.SMTPException as e: |
| print(f"SMTP Error: {e}") |
| raise HTTPException(status_code=500, detail="Failed to send email. Please check server logs.") |
| except Exception as e: |
| |
| print(f"General Error: {e}") |
| raise HTTPException(status_code=500, detail="Failed to connect to the email server. This may be due to network restrictions.") |
|
|
| return { |
| 'Message': 'Thank you, Hamza will contact you soon!' |
| } |
|
|
| |
| |
| |
| if __name__ == "__main__": |
| uvicorn.run(app, host="0.0.0.0", port=7860) |
|
|