"""Transactional + operational email via SMTP (e.g. Namecheap Private Email). If SMTP isn't configured (local dev), messages are printed to the server log so the magic-link flow and alerts still work without a real mailbox. """ import asyncio import smtplib import ssl from email.message import EmailMessage from .config import settings def _send_sync(to: str, subject: str, html: str, headers: dict | None = None): msg = EmailMessage() msg["From"] = settings.email_from msg["To"] = to msg["Subject"] = subject for name, value in (headers or {}).items(): msg[name] = value msg.set_content("This message requires an HTML-capable email client.") msg.add_alternative(html, subtype="html") if settings.smtp_port == 465: with smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port, context=ssl.create_default_context(), timeout=20) as s: s.login(settings.smtp_user, settings.smtp_password) s.send_message(msg) else: with smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=20) as s: s.starttls(context=ssl.create_default_context()) s.login(settings.smtp_user, settings.smtp_password) s.send_message(msg) async def send_email(to: str, subject: str, html: str, headers: dict | None = None): """Send an email (async wrapper). Logs instead of sending if SMTP is unset.""" if not settings.smtp_configured: print(f"✉️ [DEV email → {to}] {subject}") return try: await asyncio.to_thread(_send_sync, to, subject, html, headers) except Exception as e: print(f"⚠️ Failed to send email to {to}: {e}") async def send_commercial_email(user_id, to: str, subject: str, html: str) -> bool: """Send a commercial communication (LSSI art. 21): never to an account that unsubscribed, and always with a one-click way out (footer link plus the ``List-Unsubscribe`` header, see cloud/marketing.py). Returns False when the account had opted out and nothing was sent. """ from . import marketing if user_id is not None and await marketing.is_opted_out(user_id): return False unsub = marketing.unsubscribe_url(user_id) if user_id is not None else "" headers = {} if unsub: footer = (f'Unsubscribe from ' "upgrade and tips emails.") headers = {"List-Unsubscribe": f"<{unsub}>", "List-Unsubscribe-Post": "List-Unsubscribe=One-Click"} else: footer = "Reply to this email if you'd rather not get upgrade and tips emails." html = (f'{html}

{footer}

') await send_email(to, subject, html, headers) return True async def send_magic_link_email(email: str, link: str): if not settings.smtp_configured: print(f"✉️ [DEV magic link] {email} -> {link}") return html = f"""

Sign in to OpenShorts

Click the button below to sign in. This link expires in 15 minutes.

Sign in

If you didn't request this, ignore this email.

""" await send_email(email, "Your OpenShorts sign-in link", html) GITHUB_REPO_URL = "https://github.com/mutonby/openshorts" async def send_clips_ready_email(email: str, job_title: str, clip_count: int, dashboard_url: str): """Job-completion notice: lets the user close the tab during processing.""" title = (job_title or "Your video").strip() html = f"""

Your clips are ready 🎬

{title} produced {clip_count} viral-ready clip{'s' if clip_count != 1 else ''}. They're waiting in your dashboard.

View my clips

Enjoying OpenShorts? A star on GitHub helps a lot ⭐

""" await send_email(email, f"Your clips are ready — {title}", html) async def send_autopilot_clips_email(email: str, video_title: str, clip_count: int, scheduled_count: int, dashboard_url: str): """Autopilot finished clipping a new channel video on its own. This is the email that makes Autopilot visible: the user did nothing, and this is where they find out the work got done anyway. """ import html as _html title = _html.escape((video_title or "your new video").strip()) plural = "s" if clip_count != 1 else "" if scheduled_count: posting = (f"

The best {scheduled_count} {'is' if scheduled_count == 1 else 'are'} " f"scheduled to publish, one a day, on the accounts you picked.

") else: posting = "

Review them, tweak anything you like, and post the ones you want.

" html = f"""

Autopilot clipped your new video 🎬

You published {title} and OpenShorts already turned it into {clip_count} short{plural}.

{posting}

See my clips

You can pause Autopilot anytime from the Autopilot page in your dashboard.

""" await send_email(email, f"Autopilot: {clip_count} new short{plural} from your video", html) async def send_clips_expiring_email(email: str, clip_count: int): """Free clips enter their last day before deletion — honest loss aversion. The deadline is real (FREE_CLIP_RETENTION_DAYS); this simply makes it visible instead of deleting silently. Doubles as re-engagement for users who clipped once and went quiet. """ # The app has no /dashboard route and never has: it is a single-page app # routed entirely through the hash, and #app is what opens it (see # dashboard/src/main.jsx). /dashboard used to land on the SPA fallback, so # the button quietly showed the marketing page; now that unknown paths # return a real 404 it fails visibly. dash = f"{settings.frontend_url}/#app" n = clip_count clips = f"{n} clip" + ("s" if n != 1 else "") html = f"""

Your {clips} will be deleted tomorrow ⏳

Free clips are stored for 7 days, and {('these' if n != 1 else 'this one')} {'are' if n != 1 else 'is'} about to expire. Two ways to keep them:

Save my clips

After tomorrow they're gone for good — we can't recover deleted clips.

""" print(f"⏳ Clips-expiring email → {email} ({clips})") await send_email(email, f"Your {clips} will be deleted tomorrow", html) async def send_out_of_minutes_email(email: str, upgrade_url: str, user_id=None): """Free user hit their monthly quota — the natural upgrade moment. Mirrors the in-app upgrade modal: lead with what they lose by staying free (watermark, clips deleted after 7 days) and one concrete plan, not a generic pricing link. """ html = f"""

Your video is still waiting 🎬

You've used this month's 20 free minutes — which usually means the clips are working for you. Here's what Starter ($12/mo) changes today:

Upgrade and finish your video

Cancel anytime. Your free minutes reset on the 1st of every month.

""" if await send_commercial_email(user_id, email, "Your video is waiting — you're out of free minutes", html): print(f"✉️ Out-of-minutes upsell email → {email}") async def send_account_deleted_email(email: str): """Confirmation that an account was erased. Sent last, to an address we no longer hold: this is the only notice the user will ever get, and it is also the only signal they would have if the deletion had not been theirs. """ html = """

Your OpenShorts account has been deleted

Everything is gone: your account, your projects, your clips and their transcripts, your API keys, and the connection to any social accounts you had linked. Any active subscription was cancelled.

Two things we keep, and why:

You can sign up again any time with the same address; it will be a brand-new, empty account.

If this wasn't you, reply to this email straight away — info@openshorts.app.

""" print(f"✉️ Account-deleted confirmation → {email}") await send_email(email, "Your OpenShorts account has been deleted", html) # --------------------------------------------------------------------------- # # Lifecycle emails (cloud/lifecycle.py decides who gets which, and when). # All of them are commercial communications: send_commercial_email skips # accounts that unsubscribed and adds the unsubscribe footer and header. # --------------------------------------------------------------------------- # def _cta(url: str, label: str) -> str: return (f'

{label}

') def _first_video_line(first_video_minutes: int) -> str: if first_video_minutes > 0: return (f"

Your first video is on us: anything up to " f"{first_video_minutes} minutes is clipped whole, free.

") return "

You get 20 free minutes every month.

" async def send_welcome_email(user_id, email: str, first_video_minutes: int) -> bool: """Right after sign-up: one concrete next step, not a feature tour.""" app_url = f"{settings.frontend_url}/#app" html = f"""

Welcome to OpenShorts 👋

Paste a YouTube link (or upload a video) and you get vertical clips with captions, ready for TikTok, Reels and Shorts, in a few minutes.

{_first_video_line(first_video_minutes)} {_cta(app_url, "Clip my first video")}

Works best with people talking: podcasts, interviews, streams, tutorials.

""" return await send_commercial_email(user_id, email, "Your first video is on us", html) async def send_first_clip_email(user_id, email: str, first_video_minutes: int) -> bool: """A day after sign-up with no video processed yet.""" app_url = f"{settings.frontend_url}/#app" html = f"""

Your clips are one link away

You signed up yesterday but haven't clipped anything yet. It takes one step: paste the link of a video you already published.

{_first_video_line(first_video_minutes)} {_cta(app_url, "Paste a link")}

Stuck on something? Just reply to this email.

""" return await send_commercial_email(user_id, email, "Your first video is still free", html) async def send_winback_email(user_id, email: str, promo_code: str = "", promo_label: str = "") -> bool: """Two days after the first free video, still no plan.""" pricing = f"{settings.frontend_url}/#/pricing" if promo_code: offer = (f"

Here's {promo_label or 'a discount'}: use code " f"{promo_code} " f"at checkout.

") subject = f"{promo_label or 'A discount'} on OpenShorts, for you" else: offer = "" subject = "Keep your clips, lose the watermark" html = f"""

Liked your clips?

Free clips carry a watermark and are deleted after 7 days. Starter ($12/mo) gives you 100 minutes a month, no watermark, and clips stored forever.

{offer} {_cta(pricing, "See plans")}

Cancel anytime.

""" return await send_commercial_email(user_id, email, subject, html) async def send_checkout_recovery_email(user_id, email: str, recovery_url: str, amount_label: str = "") -> bool: """A Stripe Checkout expired unpaid. ``recovery_url`` reopens the same cart (valid 30 days, Stripe's ``after_expiration.recovery``).""" what = f"your OpenShorts plan ({amount_label})" if amount_label else "your OpenShorts plan" html = f"""

You didn't finish checking out

You started upgrading to {what} but the payment wasn't completed. Your cart is saved: one click takes you back to it.

{_cta(recovery_url, "Finish checkout")}

Card declined? PayPal and other methods are on the same page. Reply to this email if something didn't work.

""" return await send_commercial_email(user_id, email, "Your OpenShorts checkout is saved", html)