|
| 1 | +"""Outbound email delivery for password reset and other transactional mail.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import logging |
| 5 | +import smtplib |
| 6 | +from dataclasses import dataclass |
| 7 | +from email.message import EmailMessage |
| 8 | +from typing import Optional |
| 9 | +from urllib.parse import quote |
| 10 | + |
| 11 | +import requests |
| 12 | + |
| 13 | +try: |
| 14 | + from .config import EmailConfig |
| 15 | +except ImportError: |
| 16 | + from config import EmailConfig |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | +SENDGRID_API_URL = 'https://api.sendgrid.com/v3/mail/send' |
| 21 | +PASSWORD_RESET_SUBJECT = 'Reset your BiblioDrift password' |
| 22 | + |
| 23 | + |
| 24 | +@dataclass(frozen=True) |
| 25 | +class EmailSendResult: |
| 26 | + """Result of an email send attempt.""" |
| 27 | + |
| 28 | + ok: bool |
| 29 | + detail: str = '' |
| 30 | + |
| 31 | + |
| 32 | +def is_email_configured(config: EmailConfig) -> bool: |
| 33 | + """Return True when enough settings exist to send mail for the chosen provider.""" |
| 34 | + if not config.from_email or not str(config.from_email).strip(): |
| 35 | + return False |
| 36 | + |
| 37 | + provider = (config.service_provider or 'sendgrid').strip().lower() |
| 38 | + if provider == 'sendgrid': |
| 39 | + return bool(config.api_key and str(config.api_key).strip()) |
| 40 | + if provider == 'smtp': |
| 41 | + return bool(config.smtp_host and str(config.smtp_host).strip()) |
| 42 | + logger.warning("Unknown EMAIL_SERVICE '%s'; email disabled.", provider) |
| 43 | + return False |
| 44 | + |
| 45 | + |
| 46 | +def build_password_reset_url(plain_token: str, frontend_origin: str) -> str: |
| 47 | + """Build the frontend URL users open to set a new password.""" |
| 48 | + base = (frontend_origin or 'http://127.0.0.1:5500').rstrip('/') |
| 49 | + return f"{base}/pages/auth.html?token={quote(plain_token, safe='')}" |
| 50 | + |
| 51 | + |
| 52 | +def _password_reset_bodies(reset_url: str) -> tuple[str, str]: |
| 53 | + text = ( |
| 54 | + 'You requested a password reset for your BiblioDrift account.\n\n' |
| 55 | + f'Open this link to choose a new password (valid for 1 hour):\n{reset_url}\n\n' |
| 56 | + 'If you did not request this, you can ignore this email.' |
| 57 | + ) |
| 58 | + html = ( |
| 59 | + '<p>You requested a password reset for your <strong>BiblioDrift</strong> account.</p>' |
| 60 | + f'<p><a href="{reset_url}">Reset your password</a> (link expires in 1 hour).</p>' |
| 61 | + '<p>If you did not request this, you can ignore this email.</p>' |
| 62 | + ) |
| 63 | + return text, html |
| 64 | + |
| 65 | + |
| 66 | +def send_password_reset_email( |
| 67 | + to_email: str, |
| 68 | + reset_url: str, |
| 69 | + config: EmailConfig, |
| 70 | +) -> EmailSendResult: |
| 71 | + """Send the password reset message. Does not raise on provider errors.""" |
| 72 | + if not is_email_configured(config): |
| 73 | + return EmailSendResult(ok=False, detail='email_not_configured') |
| 74 | + |
| 75 | + text_body, html_body = _password_reset_bodies(reset_url) |
| 76 | + provider = (config.service_provider or 'sendgrid').strip().lower() |
| 77 | + |
| 78 | + try: |
| 79 | + if provider == 'sendgrid': |
| 80 | + return _send_via_sendgrid( |
| 81 | + to_email=to_email, |
| 82 | + subject=PASSWORD_RESET_SUBJECT, |
| 83 | + text_body=text_body, |
| 84 | + html_body=html_body, |
| 85 | + config=config, |
| 86 | + ) |
| 87 | + if provider == 'smtp': |
| 88 | + return _send_via_smtp( |
| 89 | + to_email=to_email, |
| 90 | + subject=PASSWORD_RESET_SUBJECT, |
| 91 | + text_body=text_body, |
| 92 | + html_body=html_body, |
| 93 | + config=config, |
| 94 | + ) |
| 95 | + return EmailSendResult(ok=False, detail=f'unsupported_provider:{provider}') |
| 96 | + except Exception as exc: |
| 97 | + logger.error('Password reset email failed for %s: %s', to_email, exc, exc_info=True) |
| 98 | + return EmailSendResult(ok=False, detail=str(exc)) |
| 99 | + |
| 100 | + |
| 101 | +def _send_via_sendgrid( |
| 102 | + *, |
| 103 | + to_email: str, |
| 104 | + subject: str, |
| 105 | + text_body: str, |
| 106 | + html_body: str, |
| 107 | + config: EmailConfig, |
| 108 | +) -> EmailSendResult: |
| 109 | + payload = { |
| 110 | + 'personalizations': [{'to': [{'email': to_email}]}], |
| 111 | + 'from': {'email': config.from_email}, |
| 112 | + 'subject': subject, |
| 113 | + 'content': [ |
| 114 | + {'type': 'text/plain', 'value': text_body}, |
| 115 | + {'type': 'text/html', 'value': html_body}, |
| 116 | + ], |
| 117 | + } |
| 118 | + response = requests.post( |
| 119 | + SENDGRID_API_URL, |
| 120 | + headers={ |
| 121 | + 'Authorization': f'Bearer {config.api_key}', |
| 122 | + 'Content-Type': 'application/json', |
| 123 | + }, |
| 124 | + json=payload, |
| 125 | + timeout=15, |
| 126 | + ) |
| 127 | + if response.status_code in (200, 202): |
| 128 | + return EmailSendResult(ok=True) |
| 129 | + logger.error( |
| 130 | + 'SendGrid rejected mail to %s: HTTP %s %s', |
| 131 | + to_email, |
| 132 | + response.status_code, |
| 133 | + response.text[:500], |
| 134 | + ) |
| 135 | + return EmailSendResult(ok=False, detail=f'sendgrid_http_{response.status_code}') |
| 136 | + |
| 137 | + |
| 138 | +def _send_via_smtp( |
| 139 | + *, |
| 140 | + to_email: str, |
| 141 | + subject: str, |
| 142 | + text_body: str, |
| 143 | + html_body: str, |
| 144 | + config: EmailConfig, |
| 145 | +) -> EmailSendResult: |
| 146 | + message = EmailMessage() |
| 147 | + message['Subject'] = subject |
| 148 | + message['From'] = config.from_email |
| 149 | + message['To'] = to_email |
| 150 | + message.set_content(text_body) |
| 151 | + message.add_alternative(html_body, subtype='html') |
| 152 | + |
| 153 | + host = config.smtp_host |
| 154 | + port = config.smtp_port |
| 155 | + use_tls = config.smtp_use_tls |
| 156 | + |
| 157 | + if use_tls: |
| 158 | + with smtplib.SMTP(host, port, timeout=15) as smtp: |
| 159 | + smtp.ehlo() |
| 160 | + smtp.starttls() |
| 161 | + smtp.ehlo() |
| 162 | + if config.smtp_username and config.smtp_password: |
| 163 | + smtp.login(config.smtp_username, config.smtp_password) |
| 164 | + smtp.send_message(message) |
| 165 | + else: |
| 166 | + with smtplib.SMTP(host, port, timeout=15) as smtp: |
| 167 | + if config.smtp_username and config.smtp_password: |
| 168 | + smtp.login(config.smtp_username, config.smtp_password) |
| 169 | + smtp.send_message(message) |
| 170 | + |
| 171 | + return EmailSendResult(ok=True) |
0 commit comments