Coverage for services/email_service.py: 81.55%
87 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
1"""
2Email service using Resend for transactional emails.
3"""
5from __future__ import annotations
7import html
8import logging
9import os
11import resend
13logger = logging.getLogger(__name__)
15SUPPORT_EMAIL = "support@contact.missingtable.com"
18def ensure_resend_api_key() -> None:
19 """Make sure resend.api_key is set before any Resend SDK call.
21 EmailService.__init__ sets resend.api_key as a side effect, but that
22 only runs when an outbound email is actually sent. The inbound webhook
23 and admin-reply paths can fire before any outbound has gone out — e.g.
24 immediately after a fresh pod start — at which point resend.api_key is
25 still None and the SDK raises ValidationError('API key is invalid')
26 for any API call. Set it ourselves from the env var; idempotent.
27 """
28 if resend.api_key: 28 ↛ 30line 28 didn't jump to line 30 because the condition on line 28 was always true
29 return
30 api_key = os.getenv("RESEND_API_KEY")
31 if api_key:
32 resend.api_key = api_key
35def _mask(email: str | None) -> str:
36 """Enough of an address to correlate a report, not enough to harvest."""
37 if not email or "@" not in email: 37 ↛ 38line 37 didn't jump to line 38 because the condition on line 37 was never true
38 return "***"
39 local, _, domain = email.partition("@")
40 return f"{local[:3]}***@{domain}"
43def _support_html_block() -> str:
44 """Inline support line for invite-flow HTML emails."""
45 return (
46 '<p style="color: #6b7280; font-size: 13px; margin-top: 16px;">'
47 "Need help? Contact us at "
48 f'<a href="mailto:{SUPPORT_EMAIL}" style="color: #2563eb;">{SUPPORT_EMAIL}</a>.'
49 "</p>"
50 )
53def _support_text_block() -> str:
54 """Inline support line for invite-flow plain-text emails."""
55 return f"Need help? Contact us at {SUPPORT_EMAIL}.\n\n"
58class EmailService:
59 """Thin wrapper around the Resend SDK for sending transactional emails."""
61 def __init__(self) -> None:
62 api_key = os.getenv("RESEND_API_KEY")
63 if not api_key:
64 raise ValueError("RESEND_API_KEY environment variable is required")
65 resend.api_key = api_key
66 self.from_address = os.getenv("RESEND_FROM_ADDRESS", "noreply@contact.missingtable.com")
67 self.app_base_url = os.getenv("APP_BASE_URL", "https://missingtable.com")
68 # Optional. If set, every outgoing email includes a Reply-To header
69 # pointing at this address so user replies route to a monitored
70 # inbox instead of the noreply@ from-address.
71 self.reply_to = os.getenv("RESEND_REPLY_TO") or None
72 # Resend's id for the last invitation email this instance sent, so the
73 # caller can match later delivery webhooks to the invite (SB-1814).
74 # send_invitation keeps returning a bool for its existing callers.
75 self.last_email_id: str | None = None
77 def _build_send_payload(self, to_email: str, subject: str, html: str, text: str) -> dict:
78 """Common Resend payload with optional Reply-To."""
79 payload = {
80 "from": self.from_address,
81 "to": [to_email],
82 "subject": subject,
83 "html": html,
84 "text": text,
85 }
86 if self.reply_to: 86 ↛ 88line 86 didn't jump to line 88 because the condition on line 86 was never true
87 # Resend expects a list of strings here.
88 payload["reply_to"] = [self.reply_to]
89 return payload
91 def send_password_reset(self, to_email: str, reset_token: str, username: str) -> bool:
92 """
93 Send a password reset email via Resend.
95 Args:
96 to_email: Recipient email address
97 reset_token: Signed JWT reset token
98 username: User's username (for personalisation)
100 Returns:
101 True on success, False on failure
102 """
103 reset_url = f"{self.app_base_url}/?reset_token={reset_token}"
105 html_body = f"""
106<!DOCTYPE html>
107<html>
108<head>
109 <meta charset="utf-8" />
110 <title>Reset your Missing Table password</title>
111</head>
112<body style="font-family: Arial, sans-serif; background: #f3f4f6; padding: 32px;">
113 <div style="max-width: 480px; margin: 0 auto; background: #fff; border-radius: 8px; padding: 32px;">
114 <h2 style="color: #2563eb;">Reset your password</h2>
115 <p>Hi <strong>{username}</strong>,</p>
116 <p>We received a request to reset the password for your Missing Table account.</p>
117 <p>Click the button below to choose a new password. This link expires in <strong>1 hour</strong>.</p>
118 <a href="{reset_url}"
119 style="display: inline-block; margin: 16px 0; padding: 12px 24px;
120 background: #2563eb; color: #fff; border-radius: 6px;
121 text-decoration: none; font-weight: bold;">
122 Reset Password
123 </a>
124 <p style="color: #6b7280; font-size: 13px;">
125 If you didn't request this, you can safely ignore this email — your password won't change.
126 </p>
127 <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 24px 0;" />
128 <p style="color: #9ca3af; font-size: 12px;">Missing Table · missingtable.com</p>
129 </div>
130</body>
131</html>
132"""
134 text_body = (
135 f"Hi {username},\n\n"
136 "We received a request to reset the password for your Missing Table account.\n\n"
137 f"Reset your password here (link expires in 1 hour):\n{reset_url}\n\n"
138 "If you didn't request this, you can safely ignore this email.\n\n"
139 "— Missing Table"
140 )
142 try:
143 resend.Emails.send(
144 self._build_send_payload(
145 to_email=to_email,
146 subject="Reset your Missing Table password",
147 html=html_body,
148 text=text_body,
149 )
150 )
151 logger.info("password_reset_email_sent", extra={"recipient": to_email[:3] + "***"})
152 return True
153 except Exception as e:
154 logger.error(
155 "email_send_failed",
156 extra={"email_kind": "password_reset", "recipient": _mask(to_email), "error": str(e)},
157 )
158 return False
160 def send_invitation(
161 self,
162 to_email: str,
163 invite_code: str,
164 invite_type: str | None = None,
165 expires_at: str | None = None,
166 ios_beta: bool = False,
167 testflight_email: str | None = None,
168 ) -> bool:
169 """
170 Send an invitation email with a redemption link.
172 Args:
173 to_email: Recipient email address
174 invite_code: 12-char invite code generated by InviteService
175 invite_type: e.g. "club_fan", "team_manager" (used for subject framing)
176 expires_at: ISO datetime string for when the code expires
177 (rendered as a friendly date in the body if provided)
178 ios_beta: Add the iPhone beta (TestFlight) steps (SB-1314)
179 testflight_email: Apple Account address TestFlight will write to;
180 defaults to to_email
182 Returns:
183 True on success, False on failure
184 """
185 redemption_url = f"{self.app_base_url}/?code={invite_code}"
187 # Friendly role label for the subject; falls back to a generic line.
188 role_label = {
189 "club_manager": "club manager",
190 "club_fan": "club follower",
191 "team_manager": "team manager",
192 "team_player": "team player",
193 "team_fan": "team follower",
194 }.get(invite_type or "", "")
195 subject = (
196 f"You're invited to Missing Table as a {role_label}" if role_label else "You're invited to Missing Table"
197 )
199 # Optional expiry line.
200 expiry_html = ""
201 expiry_text = ""
202 if expires_at: 202 ↛ 203line 202 didn't jump to line 203 because the condition on line 202 was never true
203 try:
204 from datetime import datetime as _dt
206 # Accept "2026-05-29T12:34:56+00:00" or trailing Z.
207 normalized = expires_at.replace("Z", "+00:00")
208 expires_dt = _dt.fromisoformat(normalized)
209 expiry_str = expires_dt.strftime("%b %-d, %Y")
210 expiry_html = (
211 f'<p style="color: #6b7280; font-size: 13px;">'
212 f"This invitation expires on <strong>{expiry_str}</strong>.</p>"
213 )
214 expiry_text = f"This invitation expires on {expiry_str}.\n\n"
215 except Exception:
216 # Bad input format — skip the line rather than fail the send.
217 pass
219 # iPhone beta steps (SB-1314). Apple sends its own TestFlight email,
220 # often to a different address than this one, so name it.
221 ios_html = ""
222 ios_text = ""
223 if ios_beta:
224 from html import escape as _escape
226 tf_email = testflight_email or to_email
227 ios_html = f"""
228 <h3 style="color: #111827; margin-top: 24px;">Get the iPhone app (beta)</h3>
229 <ol style="padding-left: 20px; color: #374151;">
230 <li>Watch for an email from Apple TestFlight sent to
231 <strong>{_escape(tf_email)}</strong>.</li>
232 <li>Install TestFlight from the App Store, then accept the invitation
233 in that email to install Missing Table.</li>
234 <li>Open Missing Table and sign up with this code:
235 <strong>{invite_code}</strong></li>
236 </ol>
237"""
238 ios_text = (
239 "Get the iPhone app (beta):\n"
240 f"1. Watch for an email from Apple TestFlight sent to {tf_email}.\n"
241 "2. Install TestFlight from the App Store, then accept the "
242 "invitation in that email to install Missing Table.\n"
243 f"3. Open Missing Table and sign up with this code: {invite_code}\n\n"
244 )
246 # Club chat channels (SB-1671): point at the profile card, never at an
247 # invite link. Emails get forwarded; the card shows the link only to
248 # people the club's rules let in, and always the current one.
249 channels_html = ""
250 channels_text = ""
251 if invite_type in ("club_fan", "team_fan", "team_player"):
252 channels_html = (
253 '<p style="color: #374151;">If your club runs chat channels, you will find them '
254 "in Missing Table under <strong>Profile → Community channels</strong>.</p>"
255 )
256 channels_text = (
257 "If your club runs chat channels, you will find them in Missing Table "
258 "under Profile -> Community channels.\n\n"
259 )
261 html_body = f"""
262<!DOCTYPE html>
263<html>
264<head>
265 <meta charset="utf-8" />
266 <title>You're invited to Missing Table</title>
267</head>
268<body style="font-family: Arial, sans-serif; background: #f3f4f6; padding: 32px;">
269 <div style="max-width: 480px; margin: 0 auto; background: #fff; border-radius: 8px; padding: 32px;">
270 <h2 style="color: #2563eb;">You're invited! ⚽️</h2>
271 <p>Hi there,</p>
272 <p>An admin at Missing Table created an invitation for you. Click the
273 button below to set up your account.</p>
274 <a href="{redemption_url}"
275 style="display: inline-block; margin: 16px 0; padding: 12px 24px;
276 background: #2563eb; color: #fff; border-radius: 6px;
277 text-decoration: none; font-weight: bold;">
278 Accept Invitation
279 </a>
280 <p style="color: #6b7280; font-size: 13px;">
281 Or paste this code on the signup page: <strong>{invite_code}</strong>
282 </p>
283 {expiry_html}
284 {channels_html}
285 {ios_html}
286 {_support_html_block()}
287 <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 24px 0;" />
288 <p style="color: #9ca3af; font-size: 12px;">Missing Table · missingtable.com</p>
289 </div>
290</body>
291</html>
292"""
294 text_body = (
295 "Hi there,\n\n"
296 "An admin at Missing Table created an invitation for you. Use "
297 "the link below to set up your account:\n\n"
298 f"{redemption_url}\n\n"
299 f"Or paste this code on the signup page: {invite_code}\n\n"
300 f"{expiry_text}"
301 f"{channels_text}"
302 f"{ios_text}"
303 f"{_support_text_block()}"
304 "— Missing Table"
305 )
307 self.last_email_id = None
308 try:
309 response = resend.Emails.send(
310 self._build_send_payload(
311 to_email=to_email,
312 subject=subject,
313 html=html_body,
314 text=text_body,
315 )
316 )
317 email_id = response.get("id") if isinstance(response, dict) else None
318 self.last_email_id = email_id if isinstance(email_id, str) and email_id else None
319 logger.info(
320 "invitation_email_sent",
321 extra={
322 "recipient": to_email[:3] + "***",
323 "invite_type": invite_type,
324 },
325 )
326 return True
327 except Exception as e:
328 logger.error(
329 "email_send_failed",
330 extra={"email_kind": "invitation", "recipient": _mask(to_email), "error": str(e)},
331 )
332 return False
334 def send_invite_request_rejection(self, to_email: str, name: str) -> bool:
335 """
336 Tell a requester their join request was not approved (SB-1392).
338 Approval needs no email of its own: approving a request creates its
339 invitation, and the invitation email is the answer.
341 Args:
342 to_email: Recipient email address
343 name: Requester's name (for personalisation)
345 Returns:
346 True on success, False on failure
347 """
348 # The name is whatever the requester typed into a public form.
349 safe_name = html.escape(name)
350 html_body = f"""
351<!DOCTYPE html>
352<html>
353<head>
354 <meta charset="utf-8" />
355 <title>Your Missing Table request</title>
356</head>
357<body style="font-family: Arial, sans-serif; background: #f3f4f6; padding: 32px;">
358 <div style="max-width: 480px; margin: 0 auto; background: #fff; border-radius: 8px; padding: 32px;">
359 <h2 style="color: #111827;">About your request</h2>
360 <p>Hi <strong>{safe_name}</strong>,</p>
361 <p>Thanks for your interest in Missing Table. We're not able to approve your request to join right now.</p>
362 <p>
363 Standings, schedules and results are open to everyone at
364 <a href="{self.app_base_url}" style="color: #2563eb;">missingtable.com</a> - no account needed.
365 </p>
366 {_support_html_block()}
367 <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 24px 0;" />
368 <p style="color: #9ca3af; font-size: 12px;">Missing Table · missingtable.com</p>
369 </div>
370</body>
371</html>
372"""
374 text_body = (
375 f"Hi {name},\n\n"
376 "Thanks for your interest in Missing Table. We're not able to "
377 "approve your request to join right now.\n\n"
378 "Standings, schedules and results are open to everyone at "
379 f"{self.app_base_url} - no account needed.\n\n"
380 f"{_support_text_block()}"
381 "— Missing Table"
382 )
384 try:
385 resend.Emails.send(
386 self._build_send_payload(
387 to_email=to_email,
388 subject="Your Missing Table request",
389 html=html_body,
390 text=text_body,
391 )
392 )
393 logger.info(
394 "invite_request_rejection_email_sent",
395 extra={"recipient": _mask(to_email)},
396 )
397 return True
398 except Exception as e:
399 logger.error(
400 "email_send_failed",
401 extra={"email_kind": "invite_request_rejection", "recipient": _mask(to_email), "error": str(e)},
402 )
403 return False