first commit
This commit is contained in:
61
app/email_utils.py
Normal file
61
app/email_utils.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import os
|
||||
import smtplib
|
||||
from email.message import EmailMessage
|
||||
|
||||
|
||||
def send_email(*, to_email: str, subject: str, body_text: str):
|
||||
"""Send a plain-text email using SMTP settings from environment variables.
|
||||
|
||||
Required env vars:
|
||||
- SMTP_HOST
|
||||
- SMTP_PORT
|
||||
- SMTP_USERNAME
|
||||
- SMTP_PASSWORD
|
||||
- SMTP_FROM (defaults to SMTP_USERNAME)
|
||||
|
||||
Optional:
|
||||
- SMTP_STARTTLS (default: "1")
|
||||
- SMTP_TIMEOUT_SECONDS (default: "10")
|
||||
- SMTP_DEBUG (default: "0") - set to 1 to print SMTP conversation to console
|
||||
"""
|
||||
|
||||
host = os.environ.get("SMTP_HOST")
|
||||
port = int(os.environ.get("SMTP_PORT", "587"))
|
||||
username = os.environ.get("SMTP_USERNAME")
|
||||
password = os.environ.get("SMTP_PASSWORD")
|
||||
from_email = os.environ.get("SMTP_FROM") or username
|
||||
starttls = os.environ.get("SMTP_STARTTLS", "1").lower() in ("1", "true", "yes", "on")
|
||||
timeout = float(os.environ.get("SMTP_TIMEOUT_SECONDS", "10"))
|
||||
debug = os.environ.get("SMTP_DEBUG", "0").lower() in ("1", "true", "yes", "on")
|
||||
|
||||
missing = []
|
||||
if not host:
|
||||
missing.append("SMTP_HOST")
|
||||
if not username:
|
||||
missing.append("SMTP_USERNAME")
|
||||
if not password:
|
||||
missing.append("SMTP_PASSWORD")
|
||||
if not from_email:
|
||||
missing.append("SMTP_FROM")
|
||||
if missing:
|
||||
raise RuntimeError(
|
||||
"Missing SMTP configuration: "
|
||||
+ ", ".join(missing)
|
||||
+ ". Set them as environment variables (or in a local .env file)."
|
||||
)
|
||||
|
||||
msg = EmailMessage()
|
||||
msg["From"] = from_email
|
||||
msg["To"] = to_email
|
||||
msg["Subject"] = subject
|
||||
msg.set_content(body_text)
|
||||
|
||||
with smtplib.SMTP(host, port, timeout=timeout) as smtp:
|
||||
if debug:
|
||||
smtp.set_debuglevel(1)
|
||||
smtp.ehlo()
|
||||
if starttls:
|
||||
smtp.starttls()
|
||||
smtp.ehlo()
|
||||
smtp.login(username, password)
|
||||
smtp.send_message(msg)
|
||||
Reference in New Issue
Block a user