emailservice/mailer/services.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

103 lines
3.9 KiB
Python

import logging
import os
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
import hostinger_mail_api
from hostinger_mail_api import Configuration, ApiClient, SendApi, AccountApi, V1SendRequest, ApiException
logger = logging.getLogger(__name__)
def send_email_via_hostinger(
recipient: str,
subject: str,
text_content: str,
html_content: str = None,
bearer_token: str = None,
mailbox_resource_id: str = None,
display_name: str = None
):
"""
Sends an email using the Hostinger Mail API Python SDK.
"""
token = bearer_token or getattr(settings, 'HOSTINGER_BEARER_TOKEN', '5bee28a2a982c7713f9254014fead914ab6ef18f4cc0685ef1c9919410e9fc82')
if not token:
raise ValueError("Hostinger bearer token is missing. Please configure HOSTINGER_BEARER_TOKEN.")
config = Configuration(access_token=token)
with ApiClient(config) as api_client:
target_mailbox_id = mailbox_resource_id or getattr(settings, 'HOSTINGER_MAILBOX_RESOURCE_ID', 'ACd8456f8f9be7a07b7f1bccb636d6')
# Auto-detect mailbox resource ID if not explicitly provided
if not target_mailbox_id:
try:
account_api = AccountApi(api_client)
account_info = account_api.get_current_account()
if account_info and hasattr(account_info, 'data') and account_info.data:
mailboxes = getattr(account_info.data, 'mailboxes', []) or []
for mb in mailboxes:
sender_address = getattr(settings, 'EMAIL_HOST_USER', '')
if sender_address and getattr(mb, 'address', '') == sender_address:
target_mailbox_id = getattr(mb, 'resource_id', None)
break
if not target_mailbox_id and mailboxes:
target_mailbox_id = getattr(mailboxes[0], 'resource_id', None)
except Exception as e:
logger.warning(f"Hostinger SDK: Could not auto-detect mailbox resource ID: {e}")
if not target_mailbox_id:
raise ValueError("Hostinger Mailbox Resource ID is required.")
send_api = SendApi(api_client)
send_request = V1SendRequest(
to=[recipient],
subject=subject,
text=text_content,
html=html_content or None,
display_name=display_name or getattr(settings, 'EMAIL_DISPLAY_NAME', None)
)
logger.info(f"Hostinger SDK: Attempting to send email to {recipient} via mailbox {target_mailbox_id}")
response = send_api.send_email(
mailbox_resource_id=target_mailbox_id,
v1_send_request=send_request
)
logger.info(f"Hostinger SDK: Successfully sent email to {recipient}")
return response
def send_email_message(
recipient: str,
subject: str,
text_content: str,
html_content: str = None,
display_name: str = None
):
"""
Unified email dispatcher. Uses Hostinger Mail API SDK if BEARER_TOKEN is available,
otherwise falls back to Django SMTP backend.
"""
token = getattr(settings, 'HOSTINGER_BEARER_TOKEN', '5bee28a2a982c7713f9254014fead914ab6ef18f4cc0685ef1c9919410e9fc82')
if token:
return send_email_via_hostinger(
recipient=recipient,
subject=subject,
text_content=text_content,
html_content=html_content,
display_name=display_name
)
# Fallback to standard SMTP via Django core mail
sender = getattr(settings, 'EMAIL_HOST_USER', 'noreply@tradhox.com')
msg = EmailMultiAlternatives(
subject,
text_content,
sender,
[recipient]
)
if html_content:
msg.attach_alternative(html_content, "text/html")
logger.info(f"SMTP Fallback: Sending email to {recipient} via {getattr(settings, 'EMAIL_HOST', 'default SMTP')}")
return msg.send(fail_silently=False)