emailservice/mailer/api.py
vickytechkey 2a6a201e0b
All checks were successful
Deploy Beta (NATIVE) / deploy (push) Successful in 46s
feat: implement email service backend with Hostinger Mail API integration
2026-10-01 18:40:57 +05:30

69 lines
2.7 KiB
Python

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings
from .models import EmailLog
from .services import send_email_message
import logging
logger = logging.getLogger(__name__)
class SendEmailAPIView(APIView):
def post(self, request):
recipient = request.data.get('recipient')
template_name = request.data.get('template_name')
context = request.data.get('context', {})
subject = request.data.get('subject')
if not recipient or not template_name:
return Response({"error": "Recipient and template_name are required."}, status=status.HTTP_400_BAD_REQUEST)
# Default subjects based on template if not provided
if not subject:
if template_name == 'verification':
subject = "Verify Your Email"
elif template_name == 'password_reset':
subject = "Password Reset Request"
elif template_name == 'welcome_email':
subject = "Welcome to Tradhox Family"
else:
subject = f"Notification from Tradhox"
# Ensure logo_url is present
if 'logo_url' not in context:
context['logo_url'] = request.build_absolute_uri('/static/mailer/images/logo.png')
try:
# We assume templates are in emails/sellercentral/common/
template_path = f'emails/sellercentral/common/{template_name}.html'
html_content = render_to_string(template_path, context)
text_content = strip_tags(html_content)
send_email_message(
recipient=recipient,
subject=subject,
text_content=text_content,
html_content=html_content
)
logger.info(f"API: Successfully sent '{template_name}' email to {recipient}")
EmailLog.objects.create(
recipient=recipient,
subject=subject,
template_name=template_name,
status='success'
)
return Response({"message": "Email sent successfully"}, status=status.HTTP_200_OK)
except Exception as e:
logger.error(f"API: Failed to send '{template_name}' email to {recipient}. Error: {str(e)}", exc_info=True)
EmailLog.objects.create(
recipient=recipient,
subject=subject,
template_name=template_name,
status='failed',
error_message=str(e)
)
return Response({"error": f"Failed to send email: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)