modcomms/backend/app/services/email_service.py
michael 5629d18df4 Fix email service crash when Mailgun not configured
Add validation to check MAILGUN_API_URL has a valid protocol prefix
and MAILGUN_API_KEY is set before attempting to make HTTP request.
Returns False gracefully with warning log instead of crashing with
httpx.UnsupportedProtocol error.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-27 14:40:42 -06:00

54 lines
1.7 KiB
Python

"""Email service for sending support emails via Mailgun."""
import httpx
from app.config import settings
class EmailService:
"""Service for sending emails via Mailgun API."""
async def send_support_email(
self,
message: str,
subject: str,
user_name: str | None = None,
user_email: str | None = None,
) -> bool:
"""Send a support email via Mailgun API.
Args:
message: The message body
subject: Email subject line
user_name: Optional name of the user submitting
user_email: Optional email of the user submitting
Returns:
True if email was sent successfully, False otherwise
"""
# Validate Mailgun configuration
if not settings.MAILGUN_API_URL or not settings.MAILGUN_API_URL.startswith(
("http://", "https://")
):
print("Warning: MAILGUN_API_URL not configured or missing protocol")
return False
if not settings.MAILGUN_API_KEY:
print("Warning: MAILGUN_API_KEY not configured")
return False
body = f"From: {user_name or 'Anonymous'}\nEmail: {user_email or 'Not provided'}\n\n{message}"
async with httpx.AsyncClient() as client:
response = await client.post(
settings.MAILGUN_API_URL,
auth=("api", settings.MAILGUN_API_KEY),
data={
"from": settings.MAILGUN_FROM,
"to": settings.SUPPORT_EMAIL,
"subject": subject,
"text": body,
},
)
return response.status_code == 200
email_service = EmailService()