| # POSTMARK_API_KEY=db96eba8-a4b5-4b83-9377-2e7dcdc00d39 |
| # SMTP_USER=kyowoon.lee1924@gmail.com |
|
|
| import os |
| import logging |
| import requests |
| from concurrent.futures import ThreadPoolExecutor |
| 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') |
|
|
| app = FastAPI( |
| version="0.0.1", |
| servers=[ |
| { |
| "url": "https://leekwoon-email-api.hf.space", |
| "description": "email API", |
| } |
| ], |
| ) |
|
|
| from postmarker.core import PostmarkClient |
| postmark = PostmarkClient(server_token=os.getenv("POSTMARK_API_KEY")) |
|
|
| executor = ThreadPoolExecutor(max_workers=3) # μ΅λ 3κ°μ μ€λ λλ‘ λΉλκΈ° μμ
μ²λ¦¬ |
|
|
| def send_email_(to_email: str): |
| # postmark_api_key = os.getenv("POSTMARK_API_KEY") |
| from_email = os.getenv("SMTP_USER") # This should be your verified Postmark sender email |
|
|
| subject = "[kyobody - μλ§μμ±] μμ
μ΄ μλ£λμμ΅λλ€." |
| body = "[kyobody - μλ§μμ±] μμ
μ΄ μλ£λμμ΅λλ€.SRT νμΌμ 첨λΆνμ¬ μ λ¬λ립λλ€." |
|
|
| postmark.emails.send( |
| From=os.getenv("SMTP_USER"), |
| To=to_email, |
| Subject=subject, |
| HtmlBody=body |
| ) |
|
|
| # headers = { |
| # "Accept": "application/json", |
| # "X-Postmark-Server-Token": postmark_api_key, |
| # "Content-Type": "application/json", |
| # } |
|
|
| # data = { |
| # "From": from_email, |
| # "To": to_email, |
| # "Subject": subject, |
| # "TextBody": body, |
| # } |
|
|
| # try: |
| # print('hi') |
| # response = requests.post( |
| # "https://api.postmarkapp.com/email", |
| # headers=headers, |
| # json=data |
| # ) |
| # response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code |
| # logging.debug(f"Email successfully sent to {to_email}, Response: {response.json()}") |
|
|
| # except requests.exceptions.RequestException as e: |
| # # Log any exceptions that occur during the email sending process |
| # logging.error(f"Failed to send email to {to_email}: {str(e)}") |
| # raise e |
|
|
| @app.post("/send-email") |
| def send_email(email: str, background_tasks: BackgroundTasks): |
| try: |
| # Schedule the email sending in the background |
| background_tasks.add_task(executor.submit, send_email_, email) |
|
|
| # Respond to the client immediately |
| return JSONResponse(status_code=202, content={"message": "You will receive an email when it's done."}) |
|
|
| except Exception as e: |
| raise HTTPException(status_code=500, detail=str(e)) |
|
|