Add script for sending test message
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Send one explicit SMTP delivery test email using local .env settings."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import smtplib
|
||||
import ssl
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from email.message import EmailMessage
|
||||
from pathlib import Path
|
||||
|
||||
REQUIRED_SETTINGS = ("MAIL_HOST", "MAIL_PORT", "MAIL_USERNAME", "MAIL_PASSWORD", "MAIL_FROM")
|
||||
|
||||
|
||||
def load_dotenv(path):
|
||||
if not path.is_file():
|
||||
raise RuntimeError("Missing .env. Copy .env.example to .env and enter the SMTP settings.")
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
key, separator, value = line.partition("=")
|
||||
if separator and key.strip():
|
||||
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Send an Eternity Project SMTP test email.")
|
||||
parser.add_argument("--to", required=True, help="Recipient email address")
|
||||
args = parser.parse_args()
|
||||
|
||||
project_root = Path(__file__).resolve().parent.parent
|
||||
load_dotenv(project_root / ".env")
|
||||
missing = [setting for setting in REQUIRED_SETTINGS if not os.environ.get(setting)]
|
||||
if missing:
|
||||
raise RuntimeError(f"Missing required SMTP settings: {', '.join(missing)}")
|
||||
|
||||
message = EmailMessage()
|
||||
message["Subject"] = "Eternity Project SMTP verification"
|
||||
message["From"] = os.environ["MAIL_FROM"]
|
||||
message["To"] = args.to
|
||||
message.set_content(
|
||||
f"SMTP delivery verification completed at {datetime.now(timezone.utc).isoformat()}.\n"
|
||||
"You can now test password-reset delivery from the application."
|
||||
)
|
||||
|
||||
try:
|
||||
with smtplib.SMTP(os.environ["MAIL_HOST"], int(os.environ["MAIL_PORT"]), timeout=15) as client:
|
||||
client.ehlo()
|
||||
client.starttls(context=ssl.create_default_context())
|
||||
client.ehlo()
|
||||
client.login(os.environ["MAIL_USERNAME"], os.environ["MAIL_PASSWORD"])
|
||||
client.send_message(message)
|
||||
except (OSError, smtplib.SMTPException) as error:
|
||||
print(f"SMTP_TEST_FAILED: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(f"SMTP_TEST_SENT_TO={args.to}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except RuntimeError as error:
|
||||
print(f"SMTP_CONFIGURATION_ERROR: {error}", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
Reference in New Issue
Block a user