Spaces:
Sleeping
Sleeping
File size: 2,758 Bytes
408b7e6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | import smtplib
import socket
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from config import SMTP_SERVER, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, VITE_PILOT_REGION
from core.reporting.email_templates import get_template
from core.logger import log_debug, logger
# 🛡️ RAILWAY NETWORK PATCH: Force IPv4 for SMTP [cite: 2026-02-23, 2026-02-27]
orig_getaddrinfo = socket.getaddrinfo
def patched_getaddrinfo(*args, **kwargs):
responses = orig_getaddrinfo(*args, **kwargs)
return [res for res in responses if res[0] == socket.AF_INET]
socket.getaddrinfo = patched_getaddrinfo
class EmailService:
def __init__(self):
self.server = SMTP_SERVER
self.port = SMTP_PORT
self.user = SMTP_USER
self.password = SMTP_PASSWORD
def send_secure_report(self, receiver_email, file_paths, session_id, metrics, region="AU_VIC"):
"""Sends encrypted clinical results with localized context [cite: 2026-01-14, 2026-02-27]."""
msg = MIMEMultipart()
msg['From'] = f"LearningView Pro <{self.user}>"
msg['To'] = receiver_email
# Localized Subject [cite: 2026-02-20]
prefix = "Clinical Profile" if region == "AU_VIC" else "Holistic Progress Summary"
msg['Subject'] = f"{prefix} | Ref: {session_id}"
body = f"""
Dear Parent/Guardian,
The clinical screening session for ID {session_id} is complete.
Attached is the encrypted PDF report.
🔐 SECURITY: The password for this PDF is your session ID: {session_id}
Regional Context: {region} Compliance
Risk Score: {metrics.get('risk_score')}%
"""
msg.attach(MIMEText(body, 'plain'))
for path in file_paths:
if os.path.exists(path):
with open(path, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename={os.path.basename(path)}")
msg.attach(part)
try:
# 🚀 Hardened Port 465 Logic
with smtplib.SMTP_SSL(self.server, self.port, timeout=15) as server:
server.login(self.user, self.password)
server.send_message(msg)
log_debug(f"📧 Dispatch Success: Report sent to {receiver_email}")
return True
except Exception as e:
logger.error(f"❌ Dispatch Failed: {str(e)}")
return False
email_service = EmailService()
|