email_service.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. """Email service for sending authentication-related emails."""
  2. from __future__ import annotations
  3. import html
  4. import logging
  5. import re
  6. import secrets
  7. import smtplib
  8. import string
  9. from datetime import datetime, timezone
  10. from email.mime.image import MIMEImage
  11. from email.mime.multipart import MIMEMultipart
  12. from email.mime.text import MIMEText
  13. from typing import Any
  14. from sqlalchemy import select
  15. from sqlalchemy.ext.asyncio import AsyncSession
  16. from backend.app.models.notification_template import NotificationTemplate
  17. from backend.app.models.settings import Settings
  18. from backend.app.schemas.auth import SMTPSettings
  19. logger = logging.getLogger(__name__)
  20. def generate_secure_password(length: int = 16) -> str:
  21. """Generate a secure random password.
  22. Args:
  23. length: Length of the password (default: 16)
  24. Returns:
  25. A secure random password containing uppercase, lowercase, digits, and special characters
  26. """
  27. # Define character sets
  28. lowercase = string.ascii_lowercase
  29. uppercase = string.ascii_uppercase
  30. digits = string.digits
  31. special = "!@#$%^&*()_+-=[]{}|;:,.<>?"
  32. # Ensure at least one character from each set
  33. password_chars = [
  34. secrets.choice(lowercase),
  35. secrets.choice(uppercase),
  36. secrets.choice(digits),
  37. secrets.choice(special),
  38. ]
  39. # Fill the rest with random characters from all sets
  40. all_chars = lowercase + uppercase + digits + special
  41. password_chars.extend(secrets.choice(all_chars) for _ in range(length - 4))
  42. # Shuffle with CSPRNG — random.shuffle() is seeded from time and not cryptographically safe
  43. secrets.SystemRandom().shuffle(password_chars)
  44. return "".join(password_chars)
  45. async def get_notification_template(db: AsyncSession, event_type: str) -> NotificationTemplate | None:
  46. """Get a notification template by event type from database.
  47. Args:
  48. db: Database session
  49. event_type: Type of event (e.g., 'user_created', 'password_reset')
  50. Returns:
  51. NotificationTemplate object or None if not found
  52. """
  53. result = await db.execute(select(NotificationTemplate).where(NotificationTemplate.event_type == event_type))
  54. return result.scalar_one_or_none()
  55. def render_template(template_str: str, variables: dict[str, Any]) -> str:
  56. """Render a template string with variables.
  57. Args:
  58. template_str: Template string with {variable} placeholders
  59. variables: Dictionary of variables to substitute
  60. Returns:
  61. Rendered template string
  62. """
  63. result = template_str
  64. for key, value in variables.items():
  65. result = result.replace("{" + key + "}", str(value) if value is not None else "")
  66. # Remove any remaining unreplaced placeholders (case-insensitive, alphanumeric + underscore)
  67. result = re.sub(r"\{[a-zA-Z0-9_]+\}", "", result)
  68. return result
  69. async def get_smtp_settings(db: AsyncSession) -> SMTPSettings | None:
  70. """Get SMTP settings from database.
  71. Args:
  72. db: Database session
  73. Returns:
  74. SMTPSettings object or None if not configured
  75. """
  76. # Fetch all SMTP-related settings
  77. result = await db.execute(
  78. select(Settings).where(
  79. Settings.key.in_(
  80. [
  81. "smtp_host",
  82. "smtp_port",
  83. "smtp_username",
  84. "smtp_password",
  85. "smtp_use_tls",
  86. "smtp_security",
  87. "smtp_auth_enabled",
  88. "smtp_from_email",
  89. "smtp_from_name",
  90. ]
  91. )
  92. )
  93. )
  94. settings_dict = {s.key: s.value for s in result.scalars().all()}
  95. # Check if minimum required settings are present
  96. required_keys = ["smtp_host", "smtp_port", "smtp_from_email"]
  97. if not all(key in settings_dict for key in required_keys):
  98. return None
  99. # Handle migration: convert old smtp_use_tls to smtp_security if needed
  100. smtp_security = settings_dict.get("smtp_security")
  101. if not smtp_security:
  102. # Migrate from old smtp_use_tls format
  103. smtp_use_tls = settings_dict.get("smtp_use_tls", "true").lower() == "true"
  104. smtp_security = "starttls" if smtp_use_tls else "ssl"
  105. smtp_auth_enabled = settings_dict.get("smtp_auth_enabled", "true").lower() == "true"
  106. return SMTPSettings(
  107. smtp_host=settings_dict["smtp_host"],
  108. smtp_port=int(settings_dict["smtp_port"]),
  109. smtp_username=settings_dict.get("smtp_username"),
  110. smtp_password=settings_dict.get("smtp_password"),
  111. smtp_security=smtp_security,
  112. smtp_auth_enabled=smtp_auth_enabled,
  113. smtp_from_email=settings_dict["smtp_from_email"],
  114. smtp_from_name=settings_dict.get("smtp_from_name", "BamBuddy"),
  115. )
  116. async def save_smtp_settings(db: AsyncSession, smtp_settings: SMTPSettings) -> None:
  117. """Save SMTP settings to database.
  118. Args:
  119. db: Database session
  120. smtp_settings: SMTP settings to save
  121. """
  122. from backend.app.core.db_dialect import upsert_setting
  123. settings_data = {
  124. "smtp_host": smtp_settings.smtp_host,
  125. "smtp_port": str(smtp_settings.smtp_port),
  126. "smtp_security": smtp_settings.smtp_security,
  127. "smtp_auth_enabled": "true" if smtp_settings.smtp_auth_enabled else "false",
  128. "smtp_from_email": smtp_settings.smtp_from_email,
  129. "smtp_from_name": smtp_settings.smtp_from_name,
  130. }
  131. # Only save username if auth is enabled or if provided
  132. if smtp_settings.smtp_username:
  133. settings_data["smtp_username"] = smtp_settings.smtp_username
  134. # Only save password if provided
  135. if smtp_settings.smtp_password:
  136. settings_data["smtp_password"] = smtp_settings.smtp_password
  137. for key, value in settings_data.items():
  138. await upsert_setting(db, Settings, key, value)
  139. def send_email(
  140. smtp_settings: SMTPSettings,
  141. to_email: str,
  142. subject: str,
  143. body_text: str,
  144. body_html: str | None = None,
  145. image_data: bytes | None = None,
  146. image_cid: str = "bambuddy-inline-photo",
  147. ) -> None:
  148. """Send an email using SMTP.
  149. Args:
  150. smtp_settings: SMTP configuration
  151. to_email: Recipient email address
  152. subject: Email subject
  153. body_text: Plain text body
  154. body_html: Optional HTML body
  155. image_data: Optional JPEG bytes to embed inline. The caller is
  156. responsible for putting a matching ``<img src="cid:{image_cid}">``
  157. in body_html — this just attaches the bytes under that Content-ID.
  158. image_cid: Content-ID the embedded image is referenced by in body_html.
  159. Raises:
  160. Exception: If email sending fails
  161. """
  162. if image_data and body_html:
  163. # multipart/related wraps multipart/alternative so the inline image
  164. # travels with the HTML part without becoming a visible attachment.
  165. msg = MIMEMultipart("related")
  166. msg["From"] = f"{smtp_settings.smtp_from_name} <{smtp_settings.smtp_from_email}>"
  167. msg["To"] = to_email
  168. msg["Subject"] = subject
  169. alt = MIMEMultipart("alternative")
  170. alt.attach(MIMEText(body_text, "plain"))
  171. alt.attach(MIMEText(body_html, "html"))
  172. msg.attach(alt)
  173. img = MIMEImage(image_data, _subtype="jpeg")
  174. img.add_header("Content-ID", f"<{image_cid}>")
  175. img.add_header("Content-Disposition", "inline", filename="photo.jpg")
  176. msg.attach(img)
  177. else:
  178. msg = MIMEMultipart("alternative")
  179. msg["From"] = f"{smtp_settings.smtp_from_name} <{smtp_settings.smtp_from_email}>"
  180. msg["To"] = to_email
  181. msg["Subject"] = subject
  182. # Attach plain text part
  183. msg.attach(MIMEText(body_text, "plain"))
  184. # Attach HTML part if provided
  185. if body_html:
  186. msg.attach(MIMEText(body_html, "html"))
  187. # Send email
  188. try:
  189. security = smtp_settings.smtp_security
  190. auth_enabled = smtp_settings.smtp_auth_enabled
  191. # Validate username is provided when authentication is enabled
  192. if auth_enabled and smtp_settings.smtp_password:
  193. if not smtp_settings.smtp_username:
  194. raise ValueError("SMTP username is required when authentication is enabled")
  195. if security == "ssl":
  196. # Direct SSL connection (typically port 465)
  197. with smtplib.SMTP_SSL(smtp_settings.smtp_host, smtp_settings.smtp_port, timeout=10) as server:
  198. if auth_enabled and smtp_settings.smtp_password and smtp_settings.smtp_username:
  199. server.login(smtp_settings.smtp_username, smtp_settings.smtp_password)
  200. server.send_message(msg)
  201. elif security == "starttls":
  202. # STARTTLS upgrade (typically port 587)
  203. with smtplib.SMTP(smtp_settings.smtp_host, smtp_settings.smtp_port, timeout=10) as server:
  204. server.starttls()
  205. if auth_enabled and smtp_settings.smtp_password and smtp_settings.smtp_username:
  206. server.login(smtp_settings.smtp_username, smtp_settings.smtp_password)
  207. server.send_message(msg)
  208. else:
  209. # No encryption (typically port 25) - use with caution
  210. with smtplib.SMTP(smtp_settings.smtp_host, smtp_settings.smtp_port, timeout=10) as server:
  211. if auth_enabled and smtp_settings.smtp_password and smtp_settings.smtp_username:
  212. server.login(smtp_settings.smtp_username, smtp_settings.smtp_password)
  213. server.send_message(msg)
  214. logger.info(f"Email sent successfully to {to_email}")
  215. except Exception as e:
  216. logger.error(f"Failed to send email to {to_email}: {e}")
  217. raise
  218. def create_welcome_email(username: str, password: str, login_url: str) -> tuple[str, str, str]:
  219. """Create welcome email content for new user.
  220. Args:
  221. username: Username of the new user
  222. password: Auto-generated password
  223. login_url: URL to login page
  224. Returns:
  225. Tuple of (subject, text_body, html_body)
  226. """
  227. subject = "Welcome to BamBuddy - Your Account Details"
  228. text_body = f"""Welcome to BamBuddy!
  229. Your account has been created. Here are your login details:
  230. Username: {username}
  231. Password: {password}
  232. You can login at: {login_url}
  233. For security reasons, please change your password after your first login.
  234. Best regards,
  235. BamBuddy Team
  236. """
  237. html_body = f"""<!DOCTYPE html>
  238. <html>
  239. <head>
  240. <meta charset="utf-8">
  241. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  242. </head>
  243. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  244. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 20px; border-radius: 8px 8px 0 0;">
  245. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">Welcome to BamBuddy!</h1>
  246. </div>
  247. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  248. <p style="font-size: 16px;">Your account has been created. Here are your login details:</p>
  249. <div style="background: white; padding: 20px; border-radius: 4px; margin: 20px 0; border-left: 4px solid #667eea;">
  250. <p style="margin: 0 0 10px 0;"><strong>Username:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{username}</code></p>
  251. <p style="margin: 0;"><strong>Password:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{password}</code></p>
  252. </div>
  253. <div style="text-align: center; margin: 30px 0;">
  254. <a href="{login_url}" style="display: inline-block; background-color: #667eea; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 4px; font-weight: bold;">Login Now</a>
  255. </div>
  256. <p style="font-size: 14px; color: #666; border-top: 1px solid #ddd; padding-top: 20px; margin-top: 20px;">
  257. <strong>Security Note:</strong> For security reasons, please change your password after your first login.
  258. </p>
  259. <p style="font-size: 14px; color: #999; margin-top: 30px;">
  260. Best regards,<br>
  261. BamBuddy Team
  262. </p>
  263. </div>
  264. </body>
  265. </html>
  266. """
  267. return subject, text_body, html_body
  268. def create_password_reset_email(username: str, password: str, login_url: str) -> tuple[str, str, str]:
  269. """Create password reset email content.
  270. Args:
  271. username: Username of the user
  272. password: New auto-generated password
  273. login_url: URL to login page
  274. Returns:
  275. Tuple of (subject, text_body, html_body)
  276. """
  277. subject = "BamBuddy - Your Password Has Been Reset"
  278. text_body = f"""Your BamBuddy password has been reset.
  279. Your login details:
  280. Username: {username}
  281. New Password: {password}
  282. You can login at: {login_url}
  283. For security reasons, please change your password after logging in.
  284. If you did not request this password reset, please contact your administrator immediately.
  285. Best regards,
  286. BamBuddy Team
  287. """
  288. html_body = f"""<!DOCTYPE html>
  289. <html>
  290. <head>
  291. <meta charset="utf-8">
  292. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  293. </head>
  294. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  295. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 20px; border-radius: 8px 8px 0 0;">
  296. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">Password Reset</h1>
  297. </div>
  298. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  299. <p style="font-size: 16px;">Your BamBuddy password has been reset.</p>
  300. <div style="background: white; padding: 20px; border-radius: 4px; margin: 20px 0; border-left: 4px solid #667eea;">
  301. <p style="margin: 0 0 10px 0;"><strong>Username:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{username}</code></p>
  302. <p style="margin: 0;"><strong>New Password:</strong> <code style="background: #f0f0f0; padding: 2px 6px; border-radius: 3px;">{password}</code></p>
  303. </div>
  304. <div style="text-align: center; margin: 30px 0;">
  305. <a href="{login_url}" style="display: inline-block; background-color: #667eea; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 4px; font-weight: bold;">Login Now</a>
  306. </div>
  307. <div style="background-color: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px; margin: 20px 0;">
  308. <p style="margin: 0; font-size: 14px; color: #856404;">
  309. <strong>⚠️ Security Alert:</strong> If you did not request this password reset, please contact your administrator immediately.
  310. </p>
  311. </div>
  312. <p style="font-size: 14px; color: #666; border-top: 1px solid #ddd; padding-top: 20px; margin-top: 20px;">
  313. <strong>Security Note:</strong> For security reasons, please change your password after logging in.
  314. </p>
  315. <p style="font-size: 14px; color: #999; margin-top: 30px;">
  316. Best regards,<br>
  317. BamBuddy Team
  318. </p>
  319. </div>
  320. </body>
  321. </html>
  322. """
  323. return subject, text_body, html_body
  324. def create_password_reset_link_email(username: str, reset_url: str) -> tuple[str, str, str]:
  325. """Create a password-reset email that contains a secure link (not a plaintext password)."""
  326. subject = "BamBuddy - Password Reset Request"
  327. text_body = f"""A password reset was requested for your BamBuddy account.
  328. Username: {username}
  329. Click the link below to set a new password (valid for 1 hour):
  330. {reset_url}
  331. If you did not request this reset, you can safely ignore this email.
  332. Best regards,
  333. BamBuddy Team
  334. """
  335. html_body = f"""<!DOCTYPE html>
  336. <html>
  337. <head>
  338. <meta charset="utf-8">
  339. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  340. </head>
  341. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  342. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 20px; border-radius: 8px 8px 0 0;">
  343. <h1 style="color: #ffffff; margin: 0; font-size: 24px;">Password Reset Request</h1>
  344. </div>
  345. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  346. <p style="font-size: 16px;">A password reset was requested for your BamBuddy account (<strong>{username}</strong>).</p>
  347. <p>Click the button below to set a new password. This link is valid for <strong>1 hour</strong>.</p>
  348. <div style="text-align: center; margin: 30px 0;">
  349. <a href="{reset_url}" style="display: inline-block; background-color: #667eea; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 4px; font-weight: bold;">Reset Password</a>
  350. </div>
  351. <div style="background-color: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px; margin: 20px 0;">
  352. <p style="margin: 0; font-size: 14px; color: #856404;">
  353. <strong>Did not request this?</strong> You can safely ignore this email. Your password has not been changed.
  354. </p>
  355. </div>
  356. <p style="font-size: 14px; color: #999; margin-top: 30px;">
  357. Best regards,<br>BamBuddy Team
  358. </p>
  359. </div>
  360. </body>
  361. </html>
  362. """
  363. return subject, text_body, html_body
  364. async def create_password_reset_link_email_from_template(
  365. db: AsyncSession, username: str, reset_url: str
  366. ) -> tuple[str, str, str]:
  367. """Create password-reset link email, using DB template if configured."""
  368. template = await get_notification_template(db, "password_reset_link")
  369. if template:
  370. variables = {"username": username, "reset_url": reset_url}
  371. subject = render_template(template.subject or "BamBuddy - Password Reset Request", variables)
  372. text_body = render_template(template.body or "", variables)
  373. html_body = render_template(template.html_body or "", variables) if template.html_body else None
  374. if not html_body:
  375. _, text_body, html_body = create_password_reset_link_email(username, reset_url)
  376. return subject, text_body, html_body
  377. return subject, text_body, html_body
  378. return create_password_reset_link_email(username, reset_url)
  379. async def create_welcome_email_from_template(
  380. db: AsyncSession, username: str, password: str, login_url: str, app_name: str = "BamBuddy"
  381. ) -> tuple[str, str, str]:
  382. """Create welcome email content using notification template from database.
  383. Args:
  384. db: Database session
  385. username: Username of the new user
  386. password: Auto-generated password
  387. login_url: URL to login page
  388. app_name: Application name (default: BamBuddy)
  389. Returns:
  390. Tuple of (subject, text_body, html_body)
  391. """
  392. # Try to get template from database
  393. template = await get_notification_template(db, "user_created")
  394. if template:
  395. # Render template with variables
  396. variables = {
  397. "app_name": app_name,
  398. "username": username,
  399. "password": password,
  400. "login_url": login_url,
  401. }
  402. subject = render_template(template.title_template, variables)
  403. text_body = render_template(template.body_template, variables)
  404. # Create HTML version with embedded login button
  405. # Escape text_body to prevent XSS vulnerabilities and convert newlines to <br> tags
  406. escaped_text_body = html.escape(text_body).replace("\n", "<br>\n")
  407. html_body = f"""<!DOCTYPE html>
  408. <html>
  409. <head>
  410. <meta charset="utf-8">
  411. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  412. </head>
  413. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  414. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 30px; border-radius: 8px 8px 0 0;">
  415. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">{html.escape(subject)}</h1>
  416. </div>
  417. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  418. <div style="font-size: 16px;">{escaped_text_body}</div>
  419. <div style="text-align: center; margin: 30px 0;">
  420. <a href="{login_url}" style="display: inline-block; background-color: #667eea; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 4px; font-weight: bold;">Login Now</a>
  421. </div>
  422. </div>
  423. </body>
  424. </html>
  425. """
  426. logger.info("Using custom welcome email template from database")
  427. return subject, text_body, html_body
  428. else:
  429. # Fallback to hardcoded template
  430. logger.warning("No welcome email template found in database, using default")
  431. return create_welcome_email(username, password, login_url)
  432. async def create_password_reset_email_from_template(
  433. db: AsyncSession, username: str, password: str, login_url: str, app_name: str = "BamBuddy"
  434. ) -> tuple[str, str, str]:
  435. """Create password reset email content using notification template from database.
  436. Args:
  437. db: Database session
  438. username: Username of the user
  439. password: New auto-generated password
  440. login_url: URL to login page
  441. app_name: Application name (default: BamBuddy)
  442. Returns:
  443. Tuple of (subject, text_body, html_body)
  444. """
  445. # Try to get template from database
  446. template = await get_notification_template(db, "password_reset")
  447. if template:
  448. # Render template with variables
  449. variables = {
  450. "app_name": app_name,
  451. "username": username,
  452. "password": password,
  453. "login_url": login_url,
  454. }
  455. subject = render_template(template.title_template, variables)
  456. text_body = render_template(template.body_template, variables)
  457. # Create HTML version with embedded login button
  458. # Escape text_body to prevent XSS vulnerabilities and convert newlines to <br> tags
  459. escaped_text_body = html.escape(text_body).replace("\n", "<br>\n")
  460. html_body = f"""<!DOCTYPE html>
  461. <html>
  462. <head>
  463. <meta charset="utf-8">
  464. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  465. </head>
  466. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  467. <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background-color: #667eea; padding: 30px; border-radius: 8px 8px 0 0;">
  468. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">{html.escape(subject)}</h1>
  469. </div>
  470. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  471. <div style="font-size: 16px;">{escaped_text_body}</div>
  472. <div style="text-align: center; margin: 30px 0;">
  473. <a href="{login_url}" style="display: inline-block; background-color: #667eea; color: #ffffff; padding: 12px 30px; text-decoration: none; border-radius: 4px; font-weight: bold;">Login Now</a>
  474. </div>
  475. <div style="background-color: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px; margin: 20px 0;">
  476. <p style="margin: 0; font-size: 14px; color: #856404;">
  477. <strong>⚠️ Security Alert:</strong> If you did not request this password reset, please contact your administrator immediately.
  478. </p>
  479. </div>
  480. </div>
  481. </body>
  482. </html>
  483. """
  484. logger.info("Using custom password reset email template from database")
  485. return subject, text_body, html_body
  486. else:
  487. # Fallback to hardcoded template
  488. logger.warning("No password reset email template found in database, using default")
  489. return create_password_reset_email(username, password, login_url)
  490. async def send_user_print_notification(
  491. db: AsyncSession,
  492. event_type: str,
  493. user_email: str,
  494. username: str,
  495. variables: dict,
  496. image_data: bytes | None = None,
  497. ) -> None:
  498. """Send a print notification email to a user using Advanced Auth SMTP settings.
  499. Args:
  500. db: Database session
  501. event_type: One of 'user_print_start', 'user_print_complete', 'user_print_failed', 'user_print_stopped'
  502. user_email: Recipient email address
  503. username: Username of the recipient
  504. variables: Template variables (printer, filename, etc.)
  505. image_data: Camera snapshot bytes, if one was captured for the event.
  506. Inlined only when the template explicitly references
  507. {finish_photo_url} — same opt-in as the provider-based email path
  508. (#1792), so a user who never asked for a photo never gets one.
  509. """
  510. # Check that advanced auth is enabled (SMTP settings must be configured)
  511. smtp_settings = await get_smtp_settings(db)
  512. if not smtp_settings:
  513. logger.warning("Cannot send user print notification: SMTP settings not configured")
  514. return
  515. # Get the template
  516. template = await get_notification_template(db, event_type)
  517. if template is None:
  518. logger.warning("No template found for event type: %s", event_type)
  519. return
  520. # Add common variables (username, timestamp, app_name) merged with caller-supplied variables
  521. all_variables = {
  522. "username": username,
  523. "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
  524. "app_name": "Bambuddy",
  525. **variables,
  526. }
  527. subject = render_template(template.title_template, all_variables)
  528. text_body = render_template(template.body_template, all_variables)
  529. finish_photo_url = variables.get("finish_photo_url")
  530. inline_photo = bool(image_data and finish_photo_url and finish_photo_url in text_body)
  531. # Build HTML body — content comes entirely from the database template
  532. escaped_text_body = html.escape(text_body).replace("\n", "<br>\n")
  533. if inline_photo:
  534. escaped_url = html.escape(finish_photo_url)
  535. img_tag = (
  536. '<img src="cid:bambuddy-user-print-photo" '
  537. 'alt="Printer camera snapshot" '
  538. 'style="max-width:100%;height:auto;border:1px solid #ddd;border-radius:4px;">'
  539. )
  540. escaped_text_body = escaped_text_body.replace(escaped_url, img_tag)
  541. html_body = f"""<!DOCTYPE html>
  542. <html>
  543. <head>
  544. <meta charset="utf-8">
  545. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  546. </head>
  547. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
  548. <div style="background: linear-gradient(135deg, #1db954 0%, #158a3e 100%); background-color: #1db954; padding: 20px; border-radius: 8px 8px 0 0;">
  549. <h1 style="color: #ffffff; margin: 0; font-size: 24px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">{html.escape(subject)}</h1>
  550. </div>
  551. <div style="background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; border: 1px solid #ddd; border-top: none;">
  552. <div style="font-size: 16px;">{escaped_text_body}</div>
  553. </div>
  554. </body>
  555. </html>
  556. """
  557. try:
  558. send_email(
  559. smtp_settings,
  560. user_email,
  561. subject,
  562. text_body,
  563. html_body,
  564. image_data=image_data if inline_photo else None,
  565. image_cid="bambuddy-user-print-photo",
  566. )
  567. logger.info("Sent %s notification email to %s", event_type, user_email)
  568. except Exception as e:
  569. logger.error("Failed to send %s notification to %s: %s", event_type, user_email, e)