import os, ssl, smtplib
from dotenv import load_dotenv
from email.mime.text import MIMEText

load_dotenv()
host = os.getenv('MAIL_SERVER', 'localhost')
port = int(os.getenv('MAIL_PORT', 465))
user = os.getenv('MAIL_USERNAME')
pw   = os.getenv('MAIL_PASSWORD')
to   = os.getenv('TEST_TO')

print("Connecting to {}:{} as {} ...".format(host, port, user))
msg = MIMEText("If you can read this, LocalNerd email sending works.")
msg['Subject'] = "LocalNerd SMTP test"
msg['From'] = user
msg['To'] = to

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
    if port == 465:
        s = smtplib.SMTP_SSL(host, port, context=ctx, timeout=20)
    else:
        s = smtplib.SMTP(host, port, timeout=20)
        s.starttls(context=ctx)
    s.login(user, pw)
    s.send_message(msg)
    s.quit()
    print("SUCCESS: server accepted the email. Check inbox AND spam for:", to)
except Exception as e:
    print("FAILED:", type(e).__name__, "-", e)
