import solara, asyncio, json, pycafe
from js import fetch, encodeURIComponent, console
from solara.lab import ConfirmationDialog
# 1) Load secrets from Py.Cafe
SECRET_TOKEN = pycafe.get_secret(
"EMAIL_TOKEN",
"Shared secret for authenticating to the mailer endpoint.",
)
# Reactive form state
subject = solara.reactive("")
body = solara.reactive("")
status = solara.reactive("")
dialog_open = solara.reactive(False)
# Your Apps Script endpoint (still hard-coded here)
ENDPOINT = f"https://script.google.com/macros/s/AKfycbx{SECRET_TOKEN}/exec"
async def send_email_async():
try:
# 2) Build a GET URL with URL-encoded parameters
token = encodeURIComponent(SECRET_TOKEN)
s = encodeURIComponent(subject.value)
b = encodeURIComponent(body.value)
url = f"{ENDPOINT}?token={token}&subject={s}&body={b}"
console.log("GET →", url)
# 3) Fire the GET
resp = await fetch(url)
console.log("HTTP status:", resp.status)
# 4) Read response text
text = await resp.text()
console.log("Raw response:", text)
# 5) Parse JSON safely
try:
result = json.loads(text)
except ValueError:
result = {}
# 6) Determine outcome
if result.get("error"):
status.value = f"❌ {result['error']}"
elif result.get("status") == "OK":
status.value = "✅ Je samenvatting is verzonden!"
else:
status.value = f"❌ Unexpected response:\n{text}"
except Exception as e:
console.log("Fetch/Network error:", e)
status.value = f"❌ Network error: {e}"
finally:
# 7) Always show the popup
dialog_open.set(True)
@solara.component
def Page():
solara.Markdown("## KompassieV1 Mailer (GET-based, failsafe)")
solara.InputText("Subject:", value=subject)
solara.InputText("Message:", value=body)
solara.Button(
"Send Email",
on_click=lambda: asyncio.create_task(send_email_async())
)
ConfirmationDialog(
open=dialog_open,
title="Delivery Status",
content=status.value,
ok="OK",
on_ok=lambda: dialog_open.set(False),
cancel="Cancel",
on_cancel=lambda: dialog_open.set(False),
persistent=True,
)