CBV01 commited on
Commit
e2e9e62
Β·
1 Parent(s): a68bdec

Fix SMTP Errno 101 network unreachable error, add IPv4 forced routing, Resend HTTP API support, and bypass save option

Browse files
Files changed (2) hide show
  1. backend/main.py +289 -51
  2. frontend/src/app/admin/page.tsx +273 -106
backend/main.py CHANGED
@@ -27,6 +27,8 @@ import platform
27
  import threading
28
  from contextlib import asynccontextmanager
29
  import smtplib
 
 
30
  from email.mime.multipart import MIMEMultipart
31
  from email.mime.text import MIMEText
32
  import httpx # pyre-ignore[21]
@@ -3503,18 +3505,144 @@ def extract_pure_email(address_str: str) -> str:
3503
  return match.group(1).strip()
3504
  return address_str.strip()
3505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3506
  def get_email_credentials() -> Dict[str, Any]:
3507
- """Fetches SMTP credentials from environment variables or database system_settings."""
3508
  smtp_host = os.getenv("SMTP_HOST")
3509
  smtp_port = os.getenv("SMTP_PORT")
3510
  smtp_user = os.getenv("SMTP_USER")
3511
  smtp_pass = os.getenv("SMTP_PASS")
3512
  smtp_from = os.getenv("SMTP_FROM")
 
 
 
3513
 
3514
  # If credentials missing or partial, query system_settings
3515
  try:
3516
  conn = get_db_connection()
3517
- rows = conn.execute("SELECT key, value FROM system_settings WHERE key LIKE 'smtp_%'").fetchall()
3518
  settings = {r["key"]: r["value"] for r in rows}
3519
  if hasattr(conn, "close"): conn.close()
3520
 
@@ -3528,6 +3656,12 @@ def get_email_credentials() -> Dict[str, Any]:
3528
  smtp_pass = settings["smtp_pass"]
3529
  if not smtp_from and "smtp_from" in settings:
3530
  smtp_from = settings["smtp_from"]
 
 
 
 
 
 
3531
  except Exception as e:
3532
  log_debug(f"EMAIL: Could not load credentials from system_settings: {e}")
3533
 
@@ -3542,6 +3676,10 @@ def get_email_credentials() -> Dict[str, Any]:
3542
  from_addr = (smtp_from or f"ArkiTel Automation <{pure_user or 'arkilostudios@gmail.com'}>").strip()
3543
  envelope_from = pure_user or extract_pure_email(from_addr)
3544
 
 
 
 
 
3545
  return {
3546
  "host": host,
3547
  "port": port,
@@ -3550,45 +3688,72 @@ def get_email_credentials() -> Dict[str, Any]:
3550
  "pass": pwd,
3551
  "from": from_addr,
3552
  "envelope_from": envelope_from,
3553
- "is_configured": bool(pure_user and pwd)
 
 
 
 
 
3554
  }
3555
 
3556
  def verify_smtp_connection(host: str, port: int, user: str, pwd: str) -> tuple[bool, str]:
3557
- """Tests live connection and authentication against the SMTP server."""
3558
  clean_user = extract_pure_email(user)
3559
  clean_pwd = pwd.strip().replace(" ", "")
3560
  if not clean_user or not clean_pwd:
3561
  return False, "Missing SMTP username or password."
3562
 
3563
- try:
3564
- if port == 465:
3565
- with smtplib.SMTP_SSL(host, port, timeout=12) as server:
3566
- server.login(clean_user, clean_pwd)
3567
- else:
3568
- with smtplib.SMTP(host, port, timeout=12) as server:
3569
- server.ehlo()
3570
- server.starttls()
3571
- server.ehlo()
3572
- server.login(clean_user, clean_pwd)
3573
- return True, "SMTP connection and authentication verified successfully!"
3574
- except smtplib.SMTPAuthenticationError as auth_err:
3575
- err_msg = auth_err.smtp_error.decode("utf-8", errors="ignore") if isinstance(auth_err.smtp_error, bytes) else str(auth_err)
3576
- return False, f"Authentication rejected by {host}: {err_msg}. Note: Gmail accounts require a 16-character App Password (with 2FA enabled)."
3577
- except smtplib.SMTPConnectError as conn_err:
3578
- return False, f"Could not connect to {host}:{port}. Error: {conn_err}"
3579
- except Exception as e:
3580
- return False, f"Connection failed ({type(e).__name__}): {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3581
 
3582
  def send_smtp_email_detailed(to_email: str, subject: str, html_content: str) -> tuple[bool, str]:
3583
- """Dispatches an email via SMTP with RFC envelope separation and detailed diagnostics."""
3584
  clean_recipient = extract_pure_email(to_email)
3585
  if not clean_recipient or "@" not in clean_recipient:
3586
  return False, f"Invalid recipient address: '{to_email}'"
3587
 
3588
  creds = get_email_credentials()
3589
- if not creds["is_configured"]:
3590
- log_debug(f"EMAIL [SIMULATED]: SMTP not configured. Email to '{clean_recipient}' ('{subject}') was not sent.")
3591
- return True, "Simulated delivery (SMTP credentials not configured)"
 
 
 
 
 
 
 
3592
 
3593
  try:
3594
  msg = MIMEMultipart("alternative")
@@ -3599,15 +3764,14 @@ def send_smtp_email_detailed(to_email: str, subject: str, html_content: str) ->
3599
  part = MIMEText(html_content, "html")
3600
  msg.attach(part)
3601
 
3602
- # RFC 5321: Envelope sender must be a bare email address, NOT formatted display name
3603
  envelope_from = creds["envelope_from"] or creds["pure_user"]
3604
 
3605
  if creds["port"] == 465:
3606
- with smtplib.SMTP_SSL(creds["host"], creds["port"], timeout=14) as server:
3607
  server.login(creds["pure_user"], creds["pass"])
3608
  server.sendmail(envelope_from, [clean_recipient], msg.as_string())
3609
  else:
3610
- with smtplib.SMTP(creds["host"], creds["port"], timeout=14) as server:
3611
  server.ehlo()
3612
  server.starttls()
3613
  server.ehlo()
@@ -3624,6 +3788,12 @@ def send_smtp_email_detailed(to_email: str, subject: str, html_content: str) ->
3624
  except Exception as e:
3625
  msg = f"SMTP Delivery Error ({type(e).__name__}): {str(e)}"
3626
  log_debug(f"EMAIL [ERROR]: Failed sending '{subject}' to {clean_recipient}: {msg}")
 
 
 
 
 
 
3627
  return False, msg
3628
 
3629
  def dispatch_smtp_email(to_email: str, subject: str, html_content: str) -> bool:
@@ -3757,11 +3927,15 @@ def send_plan_activation_email_async(to_email: str, username: str, plan_name: st
3757
  t.start()
3758
 
3759
  class SmtpSettingsUpdateRequest(BaseModel):
3760
- smtp_host: str
3761
- smtp_port: int
3762
- smtp_user: str
3763
  smtp_pass: Optional[str] = None
3764
  smtp_from: Optional[str] = None
 
 
 
 
3765
 
3766
  class TestEmailRequest(BaseModel):
3767
  to_email: str
@@ -3775,29 +3949,54 @@ async def get_admin_smtp_settings(admin_id: str = Depends(get_current_admin)):
3775
  "smtp_user": creds["user"],
3776
  "smtp_from": creds["from"],
3777
  "is_configured": creds["is_configured"],
3778
- "has_password": bool(creds["pass"])
 
 
 
 
 
3779
  }
3780
 
3781
  @app.post("/api/admin/system/smtp-settings")
3782
  async def update_admin_smtp_settings(req: SmtpSettingsUpdateRequest, admin_id: str = Depends(get_current_admin)):
3783
- clean_host = (req.smtp_host or "smtp.gmail.com").strip()
3784
- clean_port = req.smtp_port if req.smtp_port else 587
3785
- clean_user = (req.smtp_user or "").strip()
3786
- clean_pass = (req.smtp_pass or "").strip().replace(" ", "")
3787
-
3788
- # If password is omitted, see if we have an existing password saved
3789
- if not clean_pass:
3790
- curr = get_email_credentials()
3791
- clean_pass = curr.get("pass", "")
3792
-
3793
- # Live verify connection before saving to database
3794
- if clean_user and clean_pass:
3795
- verified, verify_msg = verify_smtp_connection(clean_host, clean_port, clean_user, clean_pass)
3796
- if not verified:
3797
- raise HTTPException(status_code=400, detail=f"SMTP Verification Failed: {verify_msg}")
3798
-
3799
  conn = get_db_connection()
3800
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3801
  conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('smtp_host', ?)", (clean_host,))
3802
  conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('smtp_port', ?)", (str(clean_port),))
3803
  conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('smtp_user', ?)", (clean_user,))
@@ -3805,8 +4004,25 @@ async def update_admin_smtp_settings(req: SmtpSettingsUpdateRequest, admin_id: s
3805
  conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('smtp_pass', ?)", (clean_pass,))
3806
  if req.smtp_from:
3807
  conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('smtp_from', ?)", (req.smtp_from.strip(),))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3808
  if hasattr(conn, "commit"): conn.commit()
3809
- return {"status": "success", "message": "SMTP connection verified and settings saved successfully!"}
3810
  finally:
3811
  if hasattr(conn, "close"): conn.close()
3812
 
@@ -3814,7 +4030,24 @@ async def update_admin_smtp_settings(req: SmtpSettingsUpdateRequest, admin_id: s
3814
  async def send_admin_test_email(req: TestEmailRequest, admin_id: str = Depends(get_current_admin)):
3815
  creds = get_email_credentials()
3816
  if not creds["is_configured"]:
3817
- raise HTTPException(status_code=400, detail="SMTP is not fully configured. Please provide both username and password.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3818
 
3819
  test_subject = "πŸ§ͺ ArkiTel SMTP Email Test"
3820
  test_html = f"""<div style="font-family: sans-serif; background: #0b0c10; color: #fff; padding: 28px; border-radius: 16px; border: 1px solid #222;">
@@ -3829,6 +4062,11 @@ async def send_admin_test_email(req: TestEmailRequest, admin_id: str = Depends(g
3829
  if success:
3830
  return {"status": "success", "message": f"Test email successfully dispatched to {req.to_email}!"}
3831
  else:
 
 
 
 
 
3832
  raise HTTPException(status_code=400, detail=detail_msg)
3833
 
3834
  class UserVitalsUpdateRequest(BaseModel):
 
27
  import threading
28
  from contextlib import asynccontextmanager
29
  import smtplib
30
+ import socket
31
+ import ssl
32
  from email.mime.multipart import MIMEMultipart
33
  from email.mime.text import MIMEText
34
  import httpx # pyre-ignore[21]
 
3505
  return match.group(1).strip()
3506
  return address_str.strip()
3507
 
3508
+ class IPv4SMTP(smtplib.SMTP):
3509
+ """Custom SMTP client that forces IPv4 resolution to prevent [Errno 101] on Linux containers lacking IPv6 routes."""
3510
+ def _get_socket(self, host, port, timeout):
3511
+ addr_info = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
3512
+ err = None
3513
+ for res in addr_info:
3514
+ af, socktype, proto, canonname, sa = res
3515
+ sock = None
3516
+ try:
3517
+ sock = socket.socket(af, socktype, proto)
3518
+ sock.settimeout(timeout)
3519
+ sock.connect(sa)
3520
+ return sock
3521
+ except OSError as e:
3522
+ err = e
3523
+ if sock is not None:
3524
+ try:
3525
+ sock.close()
3526
+ except Exception:
3527
+ pass
3528
+ if err is not None:
3529
+ raise err
3530
+ raise OSError(f"Could not resolve IPv4 address for {host}:{port}")
3531
+
3532
+ class IPv4SMTP_SSL(smtplib.SMTP_SSL):
3533
+ """Custom SMTP_SSL client that forces IPv4 resolution to prevent [Errno 101] on Linux containers lacking IPv6 routes."""
3534
+ def _get_socket(self, host, port, timeout):
3535
+ addr_info = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
3536
+ err = None
3537
+ for res in addr_info:
3538
+ af, socktype, proto, canonname, sa = res
3539
+ sock = None
3540
+ try:
3541
+ sock = socket.socket(af, socktype, proto)
3542
+ sock.settimeout(timeout)
3543
+ sock.connect(sa)
3544
+ server_hostname = getattr(self, "_host", host) or host
3545
+ ctx = getattr(self, "context", None) or ssl.create_default_context()
3546
+ new_sock = ctx.wrap_socket(sock, server_hostname=server_hostname)
3547
+ return new_sock
3548
+ except OSError as e:
3549
+ err = e
3550
+ if sock is not None:
3551
+ try:
3552
+ sock.close()
3553
+ except Exception:
3554
+ pass
3555
+ if err is not None:
3556
+ raise err
3557
+ raise OSError(f"Could not resolve IPv4 address for {host}:{port}")
3558
+
3559
+ def is_network_blocked_error(e: Exception) -> bool:
3560
+ """Detects whether an exception stems from host-level egress blocking (e.g., Render Free Tier blocking SMTP ports 25, 465, 587)."""
3561
+ if isinstance(e, OSError):
3562
+ if getattr(e, "errno", None) in (101, 110, 111, 113): # ENETUNREACH, ETIMEDOUT, ECONNREFUSED, EHOSTUNREACH
3563
+ return True
3564
+ err_str = str(e).lower()
3565
+ return any(k in err_str for k in ["network is unreachable", "errno 101", "timed out", "timeout", "no route to host", "connection refused"])
3566
+
3567
+ def send_resend_email(api_key: str, from_addr: str, to_addr: str, subject: str, html_content: str) -> tuple[bool, str]:
3568
+ """Sends an email via the Resend HTTP REST API over Port 443 (HTTPS), which is never blocked by Render Free Tier."""
3569
+ clean_recipient = extract_pure_email(to_addr)
3570
+ if not clean_recipient or "@" not in clean_recipient:
3571
+ return False, f"Invalid recipient address: '{to_addr}'"
3572
+ clean_key = (api_key or "").strip()
3573
+ if not clean_key:
3574
+ return False, "Missing Resend API Key"
3575
+
3576
+ url = "https://api.resend.com/emails"
3577
+ headers = {
3578
+ "Authorization": f"Bearer {clean_key}",
3579
+ "Content-Type": "application/json"
3580
+ }
3581
+ clean_from = (from_addr or "").strip()
3582
+ if not clean_from:
3583
+ clean_from = "ArkiTel <onboarding@resend.dev>"
3584
+
3585
+ payload = {
3586
+ "from": clean_from,
3587
+ "to": [clean_recipient],
3588
+ "subject": subject,
3589
+ "html": html_content
3590
+ }
3591
+ try:
3592
+ with httpx.Client(timeout=14.0) as client:
3593
+ resp = client.post(url, headers=headers, json=payload)
3594
+ if resp.status_code in (200, 201):
3595
+ log_debug(f"RESEND [SUCCESS]: Dispatched '{subject}' to {clean_recipient}")
3596
+ return True, "Email successfully dispatched via Resend HTTP API!"
3597
+ else:
3598
+ data = {}
3599
+ try:
3600
+ data = resp.json()
3601
+ except Exception:
3602
+ pass
3603
+ err_msg = data.get("message") or resp.text
3604
+ log_debug(f"RESEND [ERROR]: HTTP {resp.status_code}: {err_msg}")
3605
+ return False, f"Resend API Error ({resp.status_code}): {err_msg}"
3606
+ except Exception as e:
3607
+ log_debug(f"RESEND [EXCEPTION]: {str(e)}")
3608
+ return False, f"Resend request failed: {str(e)}"
3609
+
3610
+ def verify_resend_connection(api_key: str) -> tuple[bool, str]:
3611
+ """Tests if a Resend API key is valid over HTTPS (Port 443)."""
3612
+ clean_key = (api_key or "").strip()
3613
+ if not clean_key:
3614
+ return False, "Missing Resend API key."
3615
+ url = "https://api.resend.com/api-keys"
3616
+ headers = {
3617
+ "Authorization": f"Bearer {clean_key}"
3618
+ }
3619
+ try:
3620
+ with httpx.Client(timeout=10.0) as client:
3621
+ resp = client.get(url, headers=headers)
3622
+ if resp.status_code == 200:
3623
+ return True, "Resend API key verified successfully! (HTTP Port 443 active)"
3624
+ elif resp.status_code == 401:
3625
+ return False, "Invalid Resend API Key. Please verify the key at resend.com/api-keys."
3626
+ else:
3627
+ return False, f"Resend API returned status {resp.status_code}: {resp.text}"
3628
+ except Exception as e:
3629
+ return False, f"Resend connection check failed: {str(e)}"
3630
+
3631
  def get_email_credentials() -> Dict[str, Any]:
3632
+ """Fetches SMTP and Resend credentials from environment variables or database system_settings."""
3633
  smtp_host = os.getenv("SMTP_HOST")
3634
  smtp_port = os.getenv("SMTP_PORT")
3635
  smtp_user = os.getenv("SMTP_USER")
3636
  smtp_pass = os.getenv("SMTP_PASS")
3637
  smtp_from = os.getenv("SMTP_FROM")
3638
+ email_provider = os.getenv("EMAIL_PROVIDER", "smtp")
3639
+ resend_api_key = os.getenv("RESEND_API_KEY")
3640
+ resend_from = os.getenv("RESEND_FROM")
3641
 
3642
  # If credentials missing or partial, query system_settings
3643
  try:
3644
  conn = get_db_connection()
3645
+ rows = conn.execute("SELECT key, value FROM system_settings WHERE key LIKE 'smtp_%' OR key LIKE 'resend_%' OR key = 'email_provider'").fetchall()
3646
  settings = {r["key"]: r["value"] for r in rows}
3647
  if hasattr(conn, "close"): conn.close()
3648
 
 
3656
  smtp_pass = settings["smtp_pass"]
3657
  if not smtp_from and "smtp_from" in settings:
3658
  smtp_from = settings["smtp_from"]
3659
+ if "email_provider" in settings:
3660
+ email_provider = settings["email_provider"]
3661
+ if not resend_api_key and "resend_api_key" in settings:
3662
+ resend_api_key = settings["resend_api_key"]
3663
+ if not resend_from and "resend_from" in settings:
3664
+ resend_from = settings["resend_from"]
3665
  except Exception as e:
3666
  log_debug(f"EMAIL: Could not load credentials from system_settings: {e}")
3667
 
 
3676
  from_addr = (smtp_from or f"ArkiTel Automation <{pure_user or 'arkilostudios@gmail.com'}>").strip()
3677
  envelope_from = pure_user or extract_pure_email(from_addr)
3678
 
3679
+ smtp_configured = bool(pure_user and pwd)
3680
+ resend_configured = bool(resend_api_key and resend_api_key.strip())
3681
+ is_configured = (email_provider == "resend" and resend_configured) or (email_provider == "smtp" and smtp_configured) or smtp_configured or resend_configured
3682
+
3683
  return {
3684
  "host": host,
3685
  "port": port,
 
3688
  "pass": pwd,
3689
  "from": from_addr,
3690
  "envelope_from": envelope_from,
3691
+ "email_provider": email_provider,
3692
+ "resend_api_key": resend_api_key or "",
3693
+ "resend_from": resend_from or "ArkiTel <onboarding@resend.dev>",
3694
+ "smtp_configured": smtp_configured,
3695
+ "resend_configured": resend_configured,
3696
+ "is_configured": is_configured
3697
  }
3698
 
3699
  def verify_smtp_connection(host: str, port: int, user: str, pwd: str) -> tuple[bool, str]:
3700
+ """Tests live connection and authentication against the SMTP server using IPv4."""
3701
  clean_user = extract_pure_email(user)
3702
  clean_pwd = pwd.strip().replace(" ", "")
3703
  if not clean_user or not clean_pwd:
3704
  return False, "Missing SMTP username or password."
3705
 
3706
+ ports_to_try = [port]
3707
+ if port == 587 and 465 not in ports_to_try:
3708
+ ports_to_try.append(465)
3709
+ elif port == 465 and 587 not in ports_to_try:
3710
+ ports_to_try.append(587)
3711
+
3712
+ last_err = None
3713
+ for current_port in ports_to_try:
3714
+ try:
3715
+ if current_port == 465:
3716
+ with IPv4SMTP_SSL(host, current_port, timeout=12) as server:
3717
+ server.login(clean_user, clean_pwd)
3718
+ else:
3719
+ with IPv4SMTP(host, current_port, timeout=12) as server:
3720
+ server.ehlo()
3721
+ server.starttls()
3722
+ server.ehlo()
3723
+ server.login(clean_user, clean_pwd)
3724
+ port_msg = f" (via Port {current_port})" if current_port != port else ""
3725
+ return True, f"SMTP connection and authentication verified successfully!{port_msg}"
3726
+ except smtplib.SMTPAuthenticationError as auth_err:
3727
+ err_msg = auth_err.smtp_error.decode("utf-8", errors="ignore") if isinstance(auth_err.smtp_error, bytes) else str(auth_err)
3728
+ return False, f"Authentication rejected by {host}: {err_msg}. Note: Gmail accounts require a 16-character App Password (with 2FA enabled)."
3729
+ except Exception as e:
3730
+ last_err = e
3731
+ continue
3732
+
3733
+ if last_err:
3734
+ if is_network_blocked_error(last_err):
3735
+ return False, f"HOST_NETWORK_BLOCKED: Connection to {host}:{port} failed ({type(last_err).__name__}: {str(last_err)}). Outbound SMTP ports (587, 465, 25) are blocked by your cloud provider (Render Free Tier blocks direct SMTP). We recommend switching to the Resend API (HTTP Port 443) which works seamlessly on Render, or upgrading to a paid host/VPS."
3736
+ return False, f"Connection to {host}:{port} failed ({type(last_err).__name__}): {str(last_err)}"
3737
+
3738
+ return False, f"Could not connect to {host}:{port}"
3739
 
3740
  def send_smtp_email_detailed(to_email: str, subject: str, html_content: str) -> tuple[bool, str]:
3741
+ """Dispatches an email via configured provider: Resend HTTP API or SMTP."""
3742
  clean_recipient = extract_pure_email(to_email)
3743
  if not clean_recipient or "@" not in clean_recipient:
3744
  return False, f"Invalid recipient address: '{to_email}'"
3745
 
3746
  creds = get_email_credentials()
3747
+
3748
+ # If Resend is selected as provider or if Resend key is configured and SMTP is missing
3749
+ if creds.get("email_provider") == "resend" or (creds.get("resend_configured") and not creds.get("smtp_configured")):
3750
+ resend_key = creds.get("resend_api_key", "")
3751
+ resend_from = creds.get("resend_from") or creds.get("from") or "ArkiTel <onboarding@resend.dev>"
3752
+ return send_resend_email(resend_key, resend_from, clean_recipient, subject, html_content)
3753
+
3754
+ if not creds.get("smtp_configured"):
3755
+ log_debug(f"EMAIL [SIMULATED]: Email service not configured. Email to '{clean_recipient}' ('{subject}') was not sent.")
3756
+ return True, "Simulated delivery (email credentials not configured)"
3757
 
3758
  try:
3759
  msg = MIMEMultipart("alternative")
 
3764
  part = MIMEText(html_content, "html")
3765
  msg.attach(part)
3766
 
 
3767
  envelope_from = creds["envelope_from"] or creds["pure_user"]
3768
 
3769
  if creds["port"] == 465:
3770
+ with IPv4SMTP_SSL(creds["host"], creds["port"], timeout=14) as server:
3771
  server.login(creds["pure_user"], creds["pass"])
3772
  server.sendmail(envelope_from, [clean_recipient], msg.as_string())
3773
  else:
3774
+ with IPv4SMTP(creds["host"], creds["port"], timeout=14) as server:
3775
  server.ehlo()
3776
  server.starttls()
3777
  server.ehlo()
 
3788
  except Exception as e:
3789
  msg = f"SMTP Delivery Error ({type(e).__name__}): {str(e)}"
3790
  log_debug(f"EMAIL [ERROR]: Failed sending '{subject}' to {clean_recipient}: {msg}")
3791
+ # Automatic fallback: if host blocks SMTP port and Resend API key is available, dispatch via Resend!
3792
+ if creds.get("resend_configured") and is_network_blocked_error(e):
3793
+ log_debug("EMAIL: SMTP port blocked by host; seamlessly falling back to Resend HTTP API...")
3794
+ resend_key = creds.get("resend_api_key", "")
3795
+ resend_from = creds.get("resend_from") or creds.get("from") or "ArkiTel <onboarding@resend.dev>"
3796
+ return send_resend_email(resend_key, resend_from, clean_recipient, subject, html_content)
3797
  return False, msg
3798
 
3799
  def dispatch_smtp_email(to_email: str, subject: str, html_content: str) -> bool:
 
3927
  t.start()
3928
 
3929
  class SmtpSettingsUpdateRequest(BaseModel):
3930
+ smtp_host: Optional[str] = "smtp.gmail.com"
3931
+ smtp_port: Optional[int] = 587
3932
+ smtp_user: Optional[str] = ""
3933
  smtp_pass: Optional[str] = None
3934
  smtp_from: Optional[str] = None
3935
+ email_provider: Optional[str] = "smtp"
3936
+ resend_api_key: Optional[str] = None
3937
+ resend_from: Optional[str] = None
3938
+ skip_verify: Optional[bool] = False
3939
 
3940
  class TestEmailRequest(BaseModel):
3941
  to_email: str
 
3949
  "smtp_user": creds["user"],
3950
  "smtp_from": creds["from"],
3951
  "is_configured": creds["is_configured"],
3952
+ "has_password": bool(creds["pass"]),
3953
+ "email_provider": creds.get("email_provider", "smtp"),
3954
+ "resend_api_key_set": bool(creds.get("resend_api_key")),
3955
+ "resend_from": creds.get("resend_from", "ArkiTel <onboarding@resend.dev>"),
3956
+ "smtp_configured": creds.get("smtp_configured", False),
3957
+ "resend_configured": creds.get("resend_configured", False)
3958
  }
3959
 
3960
  @app.post("/api/admin/system/smtp-settings")
3961
  async def update_admin_smtp_settings(req: SmtpSettingsUpdateRequest, admin_id: str = Depends(get_current_admin)):
3962
+ provider = (req.email_provider or "smtp").strip().lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3963
  conn = get_db_connection()
3964
  try:
3965
+ conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('email_provider', ?)", (provider,))
3966
+
3967
+ # 1. Resend API Flow (Recommended for Render Free Tier over HTTPS Port 443)
3968
+ if provider == "resend":
3969
+ clean_resend_key = (req.resend_api_key or "").strip()
3970
+ clean_resend_from = (req.resend_from or "ArkiTel <onboarding@resend.dev>").strip()
3971
+
3972
+ if not clean_resend_key:
3973
+ curr = get_email_credentials()
3974
+ clean_resend_key = curr.get("resend_api_key", "")
3975
+
3976
+ if clean_resend_key:
3977
+ if not req.skip_verify:
3978
+ verified, verify_msg = verify_resend_connection(clean_resend_key)
3979
+ if not verified:
3980
+ raise HTTPException(status_code=400, detail=f"Resend Verification Failed: {verify_msg}")
3981
+ conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('resend_api_key', ?)", (clean_resend_key,))
3982
+
3983
+ if clean_resend_from:
3984
+ conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('resend_from', ?)", (clean_resend_from,))
3985
+
3986
+ if hasattr(conn, "commit"): conn.commit()
3987
+ return {"status": "success", "message": "Resend API configured and verified successfully over HTTPS (Port 443)!"}
3988
+
3989
+ # 2. SMTP Flow
3990
+ clean_host = (req.smtp_host or "smtp.gmail.com").strip()
3991
+ clean_port = req.smtp_port if req.smtp_port else 587
3992
+ clean_user = (req.smtp_user or "").strip()
3993
+ clean_pass = (req.smtp_pass or "").strip().replace(" ", "")
3994
+
3995
+ # If password omitted, use saved password
3996
+ if not clean_pass:
3997
+ curr = get_email_credentials()
3998
+ clean_pass = curr.get("pass", "")
3999
+
4000
  conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('smtp_host', ?)", (clean_host,))
4001
  conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('smtp_port', ?)", (str(clean_port),))
4002
  conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('smtp_user', ?)", (clean_user,))
 
4004
  conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('smtp_pass', ?)", (clean_pass,))
4005
  if req.smtp_from:
4006
  conn.execute("INSERT OR REPLACE INTO system_settings (key, value) VALUES ('smtp_from', ?)", (req.smtp_from.strip(),))
4007
+
4008
+ # Check connection if live verification requested
4009
+ if not req.skip_verify and clean_user and clean_pass:
4010
+ verified, verify_msg = verify_smtp_connection(clean_host, clean_port, clean_user, clean_pass)
4011
+ if not verified:
4012
+ # If network is blocked by host firewall (Render Free Tier blocks outbound SMTP), save settings and return informative warning
4013
+ if "HOST_NETWORK_BLOCKED" in verify_msg or is_network_blocked_error(Exception(verify_msg)):
4014
+ if hasattr(conn, "commit"): conn.commit()
4015
+ return {
4016
+ "status": "saved_with_warning",
4017
+ "warning": True,
4018
+ "network_blocked": True,
4019
+ "message": f"SMTP settings saved! Note: Outbound connection to {clean_host}:{clean_port} was blocked by the host network ([Errno 101] Network is unreachable). Render Free Tier restricts outbound SMTP ports (25, 465, 587). You can switch to the Resend API (Port 443) for guaranteed delivery on Render Free Tier, or upgrade to a paid Render/VPS instance."
4020
+ }
4021
+ else:
4022
+ raise HTTPException(status_code=400, detail=f"SMTP Verification Failed: {verify_msg}")
4023
+
4024
  if hasattr(conn, "commit"): conn.commit()
4025
+ return {"status": "success", "message": "SMTP connection and credentials verified and saved successfully!"}
4026
  finally:
4027
  if hasattr(conn, "close"): conn.close()
4028
 
 
4030
  async def send_admin_test_email(req: TestEmailRequest, admin_id: str = Depends(get_current_admin)):
4031
  creds = get_email_credentials()
4032
  if not creds["is_configured"]:
4033
+ raise HTTPException(status_code=400, detail="Email service is not configured. Please configure and save your Resend API Key or SMTP credentials first.")
4034
+
4035
+ provider = creds.get("email_provider", "smtp")
4036
+ if provider == "resend" or (creds.get("resend_configured") and not creds.get("smtp_configured")):
4037
+ resend_key = creds.get("resend_api_key", "")
4038
+ resend_from = creds.get("resend_from") or creds.get("from") or "ArkiTel <onboarding@resend.dev>"
4039
+ test_subject = "πŸ§ͺ ArkiTel Email Delivery Test (Resend API)"
4040
+ test_html = f"""<div style="font-family: sans-serif; background: #0b0c10; color: #fff; padding: 28px; border-radius: 16px; border: 1px solid #222;">
4041
+ <h2 style="color: #818cf8; margin-top: 0;">ArkiTel Email Delivery Verified!</h2>
4042
+ <p>This test email was successfully dispatched via <strong>Resend HTTPS API</strong> (Port 443).</p>
4043
+ <p><strong>Sender:</strong> {resend_from}</p>
4044
+ <p style="color: #34d399; font-weight: bold;">Your automated welcome and payment approval emails are active and working on Render!</p>
4045
+ </div>"""
4046
+ success, detail_msg = send_resend_email(resend_key, resend_from, req.to_email, test_subject, test_html)
4047
+ if success:
4048
+ return {"status": "success", "message": f"Test email successfully dispatched to {req.to_email} via Resend API!"}
4049
+ else:
4050
+ raise HTTPException(status_code=400, detail=detail_msg)
4051
 
4052
  test_subject = "πŸ§ͺ ArkiTel SMTP Email Test"
4053
  test_html = f"""<div style="font-family: sans-serif; background: #0b0c10; color: #fff; padding: 28px; border-radius: 16px; border: 1px solid #222;">
 
4062
  if success:
4063
  return {"status": "success", "message": f"Test email successfully dispatched to {req.to_email}!"}
4064
  else:
4065
+ if "Network is unreachable" in detail_msg or "Errno 101" in detail_msg:
4066
+ raise HTTPException(
4067
+ status_code=400,
4068
+ detail=f"SMTP Delivery Blocked by Host: {detail_msg}. NOTE: Render Free Tier restricts outbound SMTP ports (25, 465, 587). Please switch to the Resend API (HTTP Port 443) in Settings or upgrade your hosting instance."
4069
+ )
4070
  raise HTTPException(status_code=400, detail=detail_msg)
4071
 
4072
  class UserVitalsUpdateRequest(BaseModel):
frontend/src/app/admin/page.tsx CHANGED
@@ -116,8 +116,14 @@ export default function AdminDashboard() {
116
  smtp_user: '',
117
  smtp_pass: '',
118
  smtp_from: '',
 
 
 
 
119
  is_configured: false,
120
- has_password: false
 
 
121
  });
122
  const [loadingSmtp, setLoadingSmtp] = useState(false);
123
  const [savingSmtp, setSavingSmtp] = useState(false);
@@ -193,8 +199,13 @@ export default function AdminDashboard() {
193
  smtp_port: data.smtp_port || 587,
194
  smtp_user: data.smtp_user || '',
195
  smtp_from: data.smtp_from || '',
 
 
 
196
  is_configured: data.is_configured,
197
- has_password: data.has_password
 
 
198
  }));
199
  }
200
  } catch (e) {
@@ -3665,8 +3676,8 @@ export default function AdminDashboard() {
3665
  <Mail size={24} />
3666
  </div>
3667
  <div>
3668
- <h2 className="text-xl font-bold text-white">Email & SMTP Delivery Gateway</h2>
3669
- <p className="text-xs text-foreground/45 mt-0.5">Powers welcome onboarding emails, coupon delivery, and payment proof activation notices</p>
3670
  </div>
3671
  </div>
3672
  <div className="flex items-center gap-2">
@@ -3675,133 +3686,289 @@ export default function AdminDashboard() {
3675
  ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30'
3676
  : 'bg-amber-500/10 text-amber-400 border-amber-500/30'
3677
  }`}>
3678
- {smtpConfig.is_configured ? '● SMTP Configured & Active' : 'β—‹ SMTP Not Configured'}
 
 
3679
  </span>
3680
  </div>
3681
  </div>
3682
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3683
  {smtpStatusMsg && (
3684
- <div className={`p-3.5 rounded-2xl text-xs font-semibold ${
3685
- smtpStatusMsg.startsWith('βœ…') ? 'bg-emerald-500/10 border border-emerald-500/30 text-emerald-300' : 'bg-rose-500/10 border border-rose-500/30 text-rose-300'
 
 
 
 
3686
  }`}>
3687
  {smtpStatusMsg}
3688
  </div>
3689
  )}
3690
 
3691
- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
3692
- <div className="space-y-1.5">
3693
- <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">SMTP Host</label>
3694
- <input
3695
- type="text"
3696
- value={smtpConfig.smtp_host}
3697
- onChange={(e) => setSmtpConfig({ ...smtpConfig, smtp_host: e.target.value })}
3698
- placeholder="smtp.gmail.com"
3699
- className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500"
3700
- />
3701
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3702
 
3703
- <div className="space-y-1.5">
3704
- <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">SMTP Port (587 TLS or 465 SSL)</label>
3705
- <input
3706
- type="number"
3707
- value={smtpConfig.smtp_port}
3708
- onChange={(e) => setSmtpConfig({ ...smtpConfig, smtp_port: Number(e.target.value) })}
3709
- placeholder="587"
3710
- className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500"
3711
- />
 
 
 
3712
  </div>
 
3713
 
3714
- <div className="space-y-1.5">
3715
- <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">SMTP Username / Email</label>
3716
- <input
3717
- type="text"
3718
- value={smtpConfig.smtp_user}
3719
- onChange={(e) => setSmtpConfig({ ...smtpConfig, smtp_user: e.target.value })}
3720
- placeholder="arkilostudios@gmail.com"
3721
- className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500"
3722
- />
3723
- </div>
 
 
 
 
3724
 
3725
- <div className="space-y-1.5">
3726
- <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">
3727
- App Password {smtpConfig.has_password && <span className="text-emerald-400 font-normal">(Saved)</span>}
3728
- </label>
3729
- <input
3730
- type="password"
3731
- value={smtpConfig.smtp_pass}
3732
- onChange={(e) => setSmtpConfig({ ...smtpConfig, smtp_pass: e.target.value })}
3733
- placeholder={smtpConfig.has_password ? "β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’ (Leave blank to keep current)" : "16-char Gmail App Password"}
3734
- className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500"
3735
- />
3736
- </div>
3737
 
3738
- <div className="sm:col-span-2 space-y-1.5">
3739
- <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">Sender Display Header (From)</label>
3740
- <input
3741
- type="text"
3742
- value={smtpConfig.smtp_from}
3743
- onChange={(e) => setSmtpConfig({ ...smtpConfig, smtp_from: e.target.value })}
3744
- placeholder="ArkiTel Automation <arkilostudios@gmail.com>"
3745
- className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500"
3746
- />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3747
  </div>
3748
- </div>
3749
 
3750
- <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 pt-3 border-t border-white/10">
3751
- <button
3752
- type="button"
3753
- onClick={async () => {
3754
- setSavingSmtp(true);
3755
- setSmtpStatusMsg('');
3756
- try {
3757
- const res = await apiFetch('/api/admin/system/smtp-settings', {
3758
- method: 'POST',
3759
- body: JSON.stringify({
3760
- smtp_host: smtpConfig.smtp_host,
3761
- smtp_port: Number(smtpConfig.smtp_port),
3762
- smtp_user: smtpConfig.smtp_user,
3763
- smtp_pass: smtpConfig.smtp_pass || undefined,
3764
- smtp_from: smtpConfig.smtp_from || undefined
3765
- })
3766
- });
3767
- const data = await res.json();
3768
- if (res.ok) {
3769
- setSmtpStatusMsg(`βœ… ${data.message || 'SMTP credentials verified and saved!'}`);
3770
- setSuccessMsg('SMTP credentials verified and saved successfully!');
3771
- setTimeout(() => setSuccessMsg(''), 5000);
3772
- fetchSmtpSettings();
3773
- } else {
3774
- setSmtpStatusMsg(`❌ Verification Failed: ${data.detail || 'Failed to save SMTP'}`);
3775
- setErrorMsg(data.detail || 'Failed to save SMTP');
3776
- setTimeout(() => setErrorMsg(''), 6000);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3777
  }
3778
- } catch (e: any) {
3779
- setSmtpStatusMsg(`❌ Network Error: ${e.message}`);
3780
- } finally {
3781
- setSavingSmtp(false);
3782
- }
3783
- }}
3784
- disabled={savingSmtp || !smtpConfig.smtp_user}
3785
- className="px-6 py-3 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-xs transition-all shadow-lg shadow-indigo-600/25 active:scale-95 disabled:opacity-40 cursor-pointer flex items-center gap-2"
3786
- >
3787
- {savingSmtp ? (
3788
- <>
3789
- <div className="w-3.5 h-3.5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
3790
- <span>Verifying & Saving...</span>
3791
- </>
3792
- ) : (
3793
- <span>Verify & Save SMTP Credentials</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3794
  )}
3795
- </button>
3796
 
3797
  {/* Live Test Email Tool */}
3798
- <div className="flex items-center gap-2">
3799
  <input
3800
  type="email"
3801
  value={testEmailRecipient}
3802
  onChange={(e) => setTestEmailRecipient(e.target.value)}
3803
  placeholder="test-recipient@gmail.com"
3804
- className="bg-white/5 border border-white/10 rounded-xl px-3.5 py-2.5 text-xs text-foreground focus:outline-none focus:border-emerald-500 min-w-[200px]"
3805
  />
3806
  <button
3807
  type="button"
@@ -3830,7 +3997,7 @@ export default function AdminDashboard() {
3830
  }
3831
  }}
3832
  disabled={testingEmail}
3833
- className="px-4 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs transition-all shadow-md shadow-emerald-600/20 active:scale-95 disabled:opacity-40 flex items-center gap-1.5 cursor-pointer"
3834
  >
3835
  <Send size={13} />
3836
  <span>{testingEmail ? 'Sending...' : 'Send Test'}</span>
 
116
  smtp_user: '',
117
  smtp_pass: '',
118
  smtp_from: '',
119
+ email_provider: 'resend',
120
+ resend_api_key: '',
121
+ resend_from: 'ArkiTel <onboarding@resend.dev>',
122
+ resend_api_key_set: false,
123
  is_configured: false,
124
+ has_password: false,
125
+ smtp_configured: false,
126
+ resend_configured: false
127
  });
128
  const [loadingSmtp, setLoadingSmtp] = useState(false);
129
  const [savingSmtp, setSavingSmtp] = useState(false);
 
199
  smtp_port: data.smtp_port || 587,
200
  smtp_user: data.smtp_user || '',
201
  smtp_from: data.smtp_from || '',
202
+ email_provider: data.email_provider || 'resend',
203
+ resend_from: data.resend_from || 'ArkiTel <onboarding@resend.dev>',
204
+ resend_api_key_set: !!data.resend_api_key_set,
205
  is_configured: data.is_configured,
206
+ has_password: data.has_password,
207
+ smtp_configured: !!data.smtp_configured,
208
+ resend_configured: !!data.resend_configured
209
  }));
210
  }
211
  } catch (e) {
 
3676
  <Mail size={24} />
3677
  </div>
3678
  <div>
3679
+ <h2 className="text-xl font-bold text-white">Automated Email & Delivery Gateway</h2>
3680
+ <p className="text-xs text-foreground/45 mt-0.5">Powers welcome onboarding emails, 20% discount coupons, and payment verification notices</p>
3681
  </div>
3682
  </div>
3683
  <div className="flex items-center gap-2">
 
3686
  ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30'
3687
  : 'bg-amber-500/10 text-amber-400 border-amber-500/30'
3688
  }`}>
3689
+ {smtpConfig.is_configured
3690
+ ? `● Gateway Active (${smtpConfig.email_provider === 'resend' ? 'Resend HTTPS API' : 'SMTP'})`
3691
+ : 'β—‹ Gateway Not Configured'}
3692
  </span>
3693
  </div>
3694
  </div>
3695
 
3696
+ {/* Render Free Tier Network Egress Guidance Alert */}
3697
+ <div className="p-4 rounded-2xl bg-amber-500/10 border border-amber-500/25 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 text-xs text-amber-200">
3698
+ <div className="flex items-start gap-2.5">
3699
+ <AlertCircle size={18} className="text-amber-400 shrink-0 mt-0.5" />
3700
+ <div>
3701
+ <span className="font-bold text-amber-300">Render Free Tier Network Policy: </span>
3702
+ Render blocks outbound direct SMTP ports (25, 465, 587) returning <code className="bg-black/30 px-1 py-0.5 rounded text-amber-200">[Errno 101] Network is unreachable</code>.
3703
+ Use <span className="font-semibold text-white underline">Resend API (HTTPS Port 443)</span> for 100% reliable free sending on Render, or save your SMTP settings for when you deploy on VPS/paid hosting.
3704
+ </div>
3705
+ </div>
3706
+ </div>
3707
+
3708
+ {/* Provider Toggle Tabs */}
3709
+ <div className="flex items-center gap-3 p-1.5 bg-black/30 border border-white/10 rounded-2xl w-fit">
3710
+ <button
3711
+ type="button"
3712
+ onClick={() => setSmtpConfig({ ...smtpConfig, email_provider: 'resend' })}
3713
+ className={`px-4 py-2 rounded-xl text-xs font-bold transition-all cursor-pointer flex items-center gap-2 ${
3714
+ smtpConfig.email_provider === 'resend'
3715
+ ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-600/30'
3716
+ : 'text-foreground/60 hover:text-white'
3717
+ }`}
3718
+ >
3719
+ <Sparkles size={14} className={smtpConfig.email_provider === 'resend' ? 'text-indigo-200' : ''} />
3720
+ <span>Resend HTTP API</span>
3721
+ <span className="text-[10px] bg-white/20 px-1.5 py-0.5 rounded-full font-mono">Port 443 β€’ Free Tier</span>
3722
+ </button>
3723
+ <button
3724
+ type="button"
3725
+ onClick={() => setSmtpConfig({ ...smtpConfig, email_provider: 'smtp' })}
3726
+ className={`px-4 py-2 rounded-xl text-xs font-bold transition-all cursor-pointer flex items-center gap-2 ${
3727
+ smtpConfig.email_provider === 'smtp'
3728
+ ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-600/30'
3729
+ : 'text-foreground/60 hover:text-white'
3730
+ }`}
3731
+ >
3732
+ <Server size={14} />
3733
+ <span>Direct SMTP Server</span>
3734
+ <span className="text-[10px] bg-white/10 px-1.5 py-0.5 rounded-full font-mono">Port 587 / 465</span>
3735
+ </button>
3736
+ </div>
3737
+
3738
  {smtpStatusMsg && (
3739
+ <div className={`p-4 rounded-2xl text-xs font-semibold leading-relaxed ${
3740
+ smtpStatusMsg.startsWith('βœ…')
3741
+ ? 'bg-emerald-500/10 border border-emerald-500/30 text-emerald-300'
3742
+ : smtpStatusMsg.startsWith('⚠️')
3743
+ ? 'bg-amber-500/10 border border-amber-500/30 text-amber-300'
3744
+ : 'bg-rose-500/10 border border-rose-500/30 text-rose-300'
3745
  }`}>
3746
  {smtpStatusMsg}
3747
  </div>
3748
  )}
3749
 
3750
+ {/* RESEND PROVIDER FORM */}
3751
+ {smtpConfig.email_provider === 'resend' && (
3752
+ <div className="space-y-4 bg-white/[0.02] border border-white/5 p-5 rounded-2xl">
3753
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
3754
+ <div className="space-y-1.5">
3755
+ <div className="flex items-center justify-between">
3756
+ <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">
3757
+ Resend API Key {smtpConfig.resend_api_key_set && <span className="text-emerald-400 font-normal">(Saved)</span>}
3758
+ </label>
3759
+ <a
3760
+ href="https://resend.com/api-keys"
3761
+ target="_blank"
3762
+ rel="noreferrer"
3763
+ className="text-[10px] text-indigo-400 hover:text-indigo-300 flex items-center gap-1 font-semibold"
3764
+ >
3765
+ <span>Get free API key (3k emails/mo)</span>
3766
+ <ExternalLink size={10} />
3767
+ </a>
3768
+ </div>
3769
+ <input
3770
+ type="password"
3771
+ value={smtpConfig.resend_api_key}
3772
+ onChange={(e) => setSmtpConfig({ ...smtpConfig, resend_api_key: e.target.value })}
3773
+ placeholder={smtpConfig.resend_api_key_set ? "β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’ (Leave blank to keep saved key)" : "re_123456789..."}
3774
+ className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500 font-mono"
3775
+ />
3776
+ </div>
3777
 
3778
+ <div className="space-y-1.5">
3779
+ <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">Sender Display Header (From)</label>
3780
+ <input
3781
+ type="text"
3782
+ value={smtpConfig.resend_from}
3783
+ onChange={(e) => setSmtpConfig({ ...smtpConfig, resend_from: e.target.value })}
3784
+ placeholder="ArkiTel Automation <onboarding@resend.dev>"
3785
+ className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500"
3786
+ />
3787
+ <p className="text-[10px] text-foreground/40 mt-1">Use <code className="text-indigo-300">onboarding@resend.dev</code> for immediate testing, or your verified domain.</p>
3788
+ </div>
3789
+ </div>
3790
  </div>
3791
+ )}
3792
 
3793
+ {/* DIRECT SMTP PROVIDER FORM */}
3794
+ {smtpConfig.email_provider === 'smtp' && (
3795
+ <div className="space-y-4 bg-white/[0.02] border border-white/5 p-5 rounded-2xl">
3796
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
3797
+ <div className="space-y-1.5">
3798
+ <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">SMTP Host</label>
3799
+ <input
3800
+ type="text"
3801
+ value={smtpConfig.smtp_host}
3802
+ onChange={(e) => setSmtpConfig({ ...smtpConfig, smtp_host: e.target.value })}
3803
+ placeholder="smtp.gmail.com"
3804
+ className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500"
3805
+ />
3806
+ </div>
3807
 
3808
+ <div className="space-y-1.5">
3809
+ <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">SMTP Port (587 TLS or 465 SSL)</label>
3810
+ <input
3811
+ type="number"
3812
+ value={smtpConfig.smtp_port}
3813
+ onChange={(e) => setSmtpConfig({ ...smtpConfig, smtp_port: Number(e.target.value) })}
3814
+ placeholder="587"
3815
+ className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500"
3816
+ />
3817
+ </div>
 
 
3818
 
3819
+ <div className="space-y-1.5">
3820
+ <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">SMTP Username / Email</label>
3821
+ <input
3822
+ type="text"
3823
+ value={smtpConfig.smtp_user}
3824
+ onChange={(e) => setSmtpConfig({ ...smtpConfig, smtp_user: e.target.value })}
3825
+ placeholder="arkilostudios@gmail.com"
3826
+ className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500"
3827
+ />
3828
+ </div>
3829
+
3830
+ <div className="space-y-1.5">
3831
+ <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">
3832
+ App Password {smtpConfig.has_password && <span className="text-emerald-400 font-normal">(Saved)</span>}
3833
+ </label>
3834
+ <input
3835
+ type="password"
3836
+ value={smtpConfig.smtp_pass}
3837
+ onChange={(e) => setSmtpConfig({ ...smtpConfig, smtp_pass: e.target.value })}
3838
+ placeholder={smtpConfig.has_password ? "β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’ (Leave blank to keep current)" : "16-char Gmail App Password"}
3839
+ className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500"
3840
+ />
3841
+ </div>
3842
+
3843
+ <div className="sm:col-span-2 space-y-1.5">
3844
+ <label className="text-[11px] font-bold uppercase tracking-wider text-foreground/50">Sender Display Header (From)</label>
3845
+ <input
3846
+ type="text"
3847
+ value={smtpConfig.smtp_from}
3848
+ onChange={(e) => setSmtpConfig({ ...smtpConfig, smtp_from: e.target.value })}
3849
+ placeholder="ArkiTel Automation <arkilostudios@gmail.com>"
3850
+ className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-xs text-foreground focus:outline-none focus:border-indigo-500"
3851
+ />
3852
+ </div>
3853
+ </div>
3854
  </div>
3855
+ )}
3856
 
3857
+ {/* Action Buttons and Live Testing Tool */}
3858
+ <div className="flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-4 pt-3 border-t border-white/10">
3859
+ <div className="flex flex-wrap items-center gap-2.5">
3860
+ <button
3861
+ type="button"
3862
+ onClick={async () => {
3863
+ setSavingSmtp(true);
3864
+ setSmtpStatusMsg('');
3865
+ try {
3866
+ const payload: any = {
3867
+ email_provider: smtpConfig.email_provider,
3868
+ skip_verify: false
3869
+ };
3870
+ if (smtpConfig.email_provider === 'resend') {
3871
+ payload.resend_api_key = smtpConfig.resend_api_key || undefined;
3872
+ payload.resend_from = smtpConfig.resend_from || undefined;
3873
+ } else {
3874
+ payload.smtp_host = smtpConfig.smtp_host;
3875
+ payload.smtp_port = Number(smtpConfig.smtp_port);
3876
+ payload.smtp_user = smtpConfig.smtp_user;
3877
+ payload.smtp_pass = smtpConfig.smtp_pass || undefined;
3878
+ payload.smtp_from = smtpConfig.smtp_from || undefined;
3879
+ }
3880
+
3881
+ const res = await apiFetch('/api/admin/system/smtp-settings', {
3882
+ method: 'POST',
3883
+ body: JSON.stringify(payload)
3884
+ });
3885
+ const data = await res.json();
3886
+ if (res.ok) {
3887
+ if (data.status === 'saved_with_warning' || data.warning) {
3888
+ setSmtpStatusMsg(`⚠️ ${data.message || 'Credentials saved with host warning'}`);
3889
+ setSuccessMsg('Email settings saved (with host warning)');
3890
+ } else {
3891
+ setSmtpStatusMsg(`βœ… ${data.message || 'Email settings verified and saved!'}`);
3892
+ setSuccessMsg('Email settings verified and saved successfully!');
3893
+ }
3894
+ setTimeout(() => setSuccessMsg(''), 6000);
3895
+ fetchSmtpSettings();
3896
+ } else {
3897
+ setSmtpStatusMsg(`❌ Verification Failed: ${data.detail || 'Failed to save settings'}`);
3898
+ setErrorMsg(data.detail || 'Failed to save settings');
3899
+ setTimeout(() => setErrorMsg(''), 7000);
3900
+ }
3901
+ } catch (e: any) {
3902
+ setSmtpStatusMsg(`❌ Network Error: ${e.message}`);
3903
+ } finally {
3904
+ setSavingSmtp(false);
3905
  }
3906
+ }}
3907
+ disabled={savingSmtp || (smtpConfig.email_provider === 'smtp' && !smtpConfig.smtp_user)}
3908
+ className="px-6 py-3 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-xs transition-all shadow-lg shadow-indigo-600/25 active:scale-95 disabled:opacity-40 cursor-pointer flex items-center gap-2"
3909
+ >
3910
+ {savingSmtp ? (
3911
+ <>
3912
+ <div className="w-3.5 h-3.5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
3913
+ <span>Verifying & Saving...</span>
3914
+ </>
3915
+ ) : (
3916
+ <span>Verify & Save {smtpConfig.email_provider === 'resend' ? 'Resend API' : 'SMTP Credentials'}</span>
3917
+ )}
3918
+ </button>
3919
+
3920
+ {smtpConfig.email_provider === 'smtp' && (
3921
+ <button
3922
+ type="button"
3923
+ onClick={async () => {
3924
+ setSavingSmtp(true);
3925
+ setSmtpStatusMsg('');
3926
+ try {
3927
+ const res = await apiFetch('/api/admin/system/smtp-settings', {
3928
+ method: 'POST',
3929
+ body: JSON.stringify({
3930
+ email_provider: 'smtp',
3931
+ smtp_host: smtpConfig.smtp_host,
3932
+ smtp_port: Number(smtpConfig.smtp_port),
3933
+ smtp_user: smtpConfig.smtp_user,
3934
+ smtp_pass: smtpConfig.smtp_pass || undefined,
3935
+ smtp_from: smtpConfig.smtp_from || undefined,
3936
+ skip_verify: true
3937
+ })
3938
+ });
3939
+ const data = await res.json();
3940
+ if (res.ok) {
3941
+ setSmtpStatusMsg(`βœ… SMTP credentials saved successfully (live verification bypassed for external VPS)!`);
3942
+ setSuccessMsg('SMTP settings saved successfully!');
3943
+ setTimeout(() => setSuccessMsg(''), 5000);
3944
+ fetchSmtpSettings();
3945
+ } else {
3946
+ setSmtpStatusMsg(`❌ Failed: ${data.detail || 'Could not save SMTP'}`);
3947
+ }
3948
+ } catch (e: any) {
3949
+ setSmtpStatusMsg(`❌ Error: ${e.message}`);
3950
+ } finally {
3951
+ setSavingSmtp(false);
3952
+ }
3953
+ }}
3954
+ disabled={savingSmtp || !smtpConfig.smtp_user}
3955
+ className="px-4 py-3 rounded-xl bg-white/5 hover:bg-white/10 text-foreground/80 hover:text-white font-bold text-xs transition-all border border-white/10 active:scale-95 disabled:opacity-40 cursor-pointer flex items-center gap-1.5"
3956
+ title="Save SMTP credentials directly into the database without running a live connection test"
3957
+ >
3958
+ <Shield size={13} />
3959
+ <span>Save Without Testing (Bypass Egress Check)</span>
3960
+ </button>
3961
  )}
3962
+ </div>
3963
 
3964
  {/* Live Test Email Tool */}
3965
+ <div className="flex items-center gap-2 pt-2 lg:pt-0">
3966
  <input
3967
  type="email"
3968
  value={testEmailRecipient}
3969
  onChange={(e) => setTestEmailRecipient(e.target.value)}
3970
  placeholder="test-recipient@gmail.com"
3971
+ className="bg-white/5 border border-white/10 rounded-xl px-3.5 py-2.5 text-xs text-foreground focus:outline-none focus:border-emerald-500 min-w-[210px]"
3972
  />
3973
  <button
3974
  type="button"
 
3997
  }
3998
  }}
3999
  disabled={testingEmail}
4000
+ className="px-4 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs transition-all shadow-md shadow-emerald-600/20 active:scale-95 disabled:opacity-40 flex items-center gap-1.5 cursor-pointer whitespace-nowrap"
4001
  >
4002
  <Send size={13} />
4003
  <span>{testingEmail ? 'Sending...' : 'Send Test'}</span>