from html import escape import resend from flask import current_app class EmailDeliveryError(RuntimeError): pass def send_email(*, to, subject, html, text, reply_to=None): if not current_app.config["EMAIL_DELIVERY_ENABLED"]: return {"id": "email-delivery-disabled"} resend.api_key = current_app.config["RESEND_API_KEY"] payload = { "from": current_app.config["EMAIL_FROM"], "to": [to], "subject": subject, "html": html, "text": text, } if reply_to: payload["reply_to"] = reply_to try: return resend.Emails.send(payload) except Exception as error: raise EmailDeliveryError("Email delivery failed") from error def action_email(*, to, subject, heading, body, action_label, action_url): safe_heading = escape(heading) safe_body = escape(body) safe_label = escape(action_label) safe_url = escape(action_url, quote=True) html = ( '
' f"

{safe_heading}

{safe_body}

" f'

{safe_label}

' f"

If the button does not work, copy this link:
{safe_url}

" ) text = f"{heading}\n\n{body}\n\n{action_label}: {action_url}" return send_email(to=to, subject=subject, html=html, text=text) def send_verification_email(user, raw_token): url = f"{current_app.config['APP_URL']}/verify-email?token={raw_token}" return action_email( to=user.email, subject="Verify your email", heading="Verify your email", body="Confirm your email address to activate your account.", action_label="Verify email", action_url=url, ) def send_password_reset_email(user, raw_token): url = f"{current_app.config['APP_URL']}/reset-password?token={raw_token}" return action_email( to=user.email, subject="Reset your password", heading="Reset your password", body="Use this secure link to choose a new password. If you did not request this, ignore this email.", action_label="Reset password", action_url=url, ) def send_contact_email(*, name, email, subject, message): safe_name = escape(name) safe_email = escape(email) safe_subject = escape(subject) safe_message = escape(message).replace("\n", "
") return send_email( to=current_app.config["CONTACT_EMAIL"], subject=f"Website contact: {subject}", html=( "

Contact form

" f"

From: {safe_name} ({safe_email})

" f"

Subject: {safe_subject}

" f"

{safe_message}

" ), text=f"From: {name} <{email}>\nSubject: {subject}\n\n{message}", reply_to=email, )