#!/usr/bin/env python3
import os, smtplib, ssl
from email.message import EmailMessage
from dotenv import load_dotenv

# requires * dotenv (uv add dotenv)
#          * credentials.env

# load email config if no environment variables are set
load_dotenv("credentials.env")

HOST = os.environ["SMTP_HOST"]
PORT = int(os.environ.get("SMTP_PORT", 587))
USER = os.environ["SMTP_USER"]
PASS = os.environ["SMTP_PASS"]
FROM = os.environ["SMTP_MAIL"]

msg = EmailMessage()
msg["Subject"] = "Hello from Python"
msg["From"]    = FROM
msg["To"]      = "bob@example.com"

# plain text (required)
msg.set_content("plain text message")

# html (optional)
msg.add_alternative("""
    <html><body>
      <p>message with <b>bold</b> and <i>italic</i></p>"
    </body></html>""",
    subtype="html")

# send mail
context = ssl.create_default_context()
try:
    with smtplib.SMTP(HOST, PORT) as smtp:
        smtp.starttls(context=context)
        smtp.login(USER, PASS)
        smtp.send_message(msg)
except (smtplib.SMTPException, OSError) as e:
    print(f"Failed to send email: {e}")
print("Mail sent.")
