| | import os |
| | import requests |
| | import logging |
| | from fastapi import FastAPI, HTTPException, BackgroundTasks |
| | from fastapi.responses import JSONResponse |
| | from dotenv import load_dotenv |
| |
|
| | |
| | load_dotenv() |
| |
|
| | |
| | logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') |
| |
|
| | |
| | app = FastAPI( |
| | servers=[ |
| | { |
| | "url": "https://leekwoon-email-api.hf.space", |
| | } |
| | ], |
| | ) |
| |
|
| | def send_email_via_mailgun(to_email: str, subject: str, body: str): |
| | mailgun_api_key = os.getenv("MAILGUN_API_KEY") |
| | mailgun_domain = os.getenv("MAILGUN_DOMAIN_NAME") |
| | from_email = os.getenv("FROM_EMAIL") |
| |
|
| | request_url = f"https://api.mailgun.net/v3/{mailgun_domain}/messages" |
| | |
| | try: |
| | response = requests.post( |
| | request_url, |
| | auth=("api", mailgun_api_key), |
| | data={ |
| | "from": from_email, |
| | "to": [to_email], |
| | "subject": subject, |
| | "text": body |
| | } |
| | ) |
| | response.raise_for_status() |
| | logging.debug(f"Email successfully sent to {to_email} via Mailgun") |
| |
|
| | except requests.exceptions.RequestException as e: |
| | logging.error(f"Failed to send email to {to_email} via Mailgun: {str(e)}") |
| | raise HTTPException(status_code=500, detail="Failed to send email via Mailgun") |
| |
|
| | @app.post("/send-chat-email") |
| | def send_chat_email(chat_content: str, to_email: str, background_tasks: BackgroundTasks): |
| | """ |
| | Sends an email with the provided chat content to the specified email address. |
| | |
| | Args: |
| | chat_content (str): The content of the chat to be sent. |
| | to_email (str): The email address to send the chat content to. |
| | |
| | Returns: |
| | JSONResponse: A response indicating the email sending status. |
| | """ |
| | try: |
| | |
| | email_subject = "Chat Transcript" |
| | email_body = f"{chat_content}" |
| |
|
| | |
| | background_tasks.add_task(send_email_via_mailgun, to_email, email_subject, email_body) |
| |
|
| | |
| | return JSONResponse(status_code=202, content={"message": "The email is being sent."}) |
| |
|
| | except Exception as e: |
| | |
| | raise HTTPException(status_code=500, detail=str(e)) |
| |
|