File size: 2,469 Bytes
49ee488 f996a4d de2d9d4 49ee488 f996a4d 49ee488 1f89804 de2d9d4 49ee488 de2d9d4 f996a4d de2d9d4 49ee488 de2d9d4 49ee488 de2d9d4 49ee488 de2d9d4 f996a4d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
import os
import requests
import logging
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.responses import JSONResponse
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Set up logging configuration
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# Initialize FastAPI app
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 and body
email_subject = "Chat Transcript"
email_body = f"{chat_content}"
# Schedule the email to be sent in the background
background_tasks.add_task(send_email_via_mailgun, to_email, email_subject, email_body)
# Respond to the client immediately with an acceptance message
return JSONResponse(status_code=202, content={"message": "The email is being sent."})
except Exception as e:
# Raise an HTTP 500 error if something goes wrong
raise HTTPException(status_code=500, detail=str(e))
|