51 lines
1.8 KiB
Python
51 lines
1.8 KiB
Python
import aiosmtplib
|
|
from email.mime.multipart import MIMEMultipart
|
|
from email.mime.text import MIMEText
|
|
from email.message import EmailMessage
|
|
from aiohttp import web
|
|
import logging
|
|
|
|
from retoors.services.config_service import ConfigService
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
async def send_email(app: web.Application, recipient_email: str, subject: str, body: str):
|
|
"""
|
|
Sends an email asynchronously using the configured SMTP settings.
|
|
"""
|
|
config_service: ConfigService = app["config_service"]
|
|
|
|
smtp_host = config_service.get_smtp_host()
|
|
smtp_port = config_service.get_smtp_port()
|
|
smtp_username = config_service.get_smtp_username()
|
|
smtp_password = config_service.get_smtp_password()
|
|
smtp_use_tls = config_service.get_smtp_use_tls()
|
|
smtp_sender_email = config_service.get_smtp_sender_email()
|
|
|
|
if not smtp_host or not smtp_sender_email:
|
|
logger.error("SMTP host or sender email not configured. Cannot send email.")
|
|
return
|
|
|
|
msg = MIMEMultipart('alternative')
|
|
msg["From"] = smtp_sender_email
|
|
msg["To"] = recipient_email
|
|
msg["Subject"] = subject
|
|
html_part = MIMEText(body, 'html')
|
|
msg.attach(html_part)
|
|
|
|
try:
|
|
await aiosmtplib.send(
|
|
msg,
|
|
hostname=smtp_host,
|
|
port=smtp_port,
|
|
username=smtp_username,
|
|
password=smtp_password,
|
|
use_tls=False, # Always False when using start_tls
|
|
start_tls=smtp_use_tls, # Use start_tls for explicit TLS negotiation
|
|
)
|
|
logger.info(f"Email sent successfully to {recipient_email} with subject '{subject}'")
|
|
except aiosmtplib.SMTPException as e:
|
|
logger.error(f"Failed to send email to {recipient_email}: {e}")
|
|
except Exception as e:
|
|
logger.error(f"An unexpected error occurred while sending email to {recipient_email}: {e}")
|