Create services/email_service.py
Browse files
app/services/email_service.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/services/email_service.py
|
| 2 |
+
import os
|
| 3 |
+
import smtplib
|
| 4 |
+
from email.mime.text import MIMEText
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def send_email(to_email: str, subject: str, body: str) -> None:
|
| 8 |
+
"""
|
| 9 |
+
Simple SMTP email sender.
|
| 10 |
+
|
| 11 |
+
Uses environment variables for configuration:
|
| 12 |
+
SMTP_HOST
|
| 13 |
+
SMTP_PORT
|
| 14 |
+
SMTP_USERNAME
|
| 15 |
+
SMTP_PASSWORD
|
| 16 |
+
SMTP_FROM
|
| 17 |
+
|
| 18 |
+
If SMTP_HOST or SMTP_FROM are missing, this will just print
|
| 19 |
+
the email payload and return without raising.
|
| 20 |
+
"""
|
| 21 |
+
smtp_host = os.getenv("SMTP_HOST")
|
| 22 |
+
smtp_port = int(os.getenv("SMTP_PORT", "587"))
|
| 23 |
+
smtp_username = os.getenv("SMTP_USERNAME")
|
| 24 |
+
smtp_password = os.getenv("SMTP_PASSWORD")
|
| 25 |
+
smtp_from = os.getenv("SMTP_FROM")
|
| 26 |
+
|
| 27 |
+
# If not configured, just log and exit quietly
|
| 28 |
+
if not smtp_host or not smtp_from:
|
| 29 |
+
print(
|
| 30 |
+
"[email_service] SMTP not configured. "
|
| 31 |
+
"Pretending to send email:\n"
|
| 32 |
+
f"To: {to_email}\nSubject: {subject}\n\n{body}\n"
|
| 33 |
+
)
|
| 34 |
+
return
|
| 35 |
+
|
| 36 |
+
msg = MIMEText(body)
|
| 37 |
+
msg["Subject"] = subject
|
| 38 |
+
msg["From"] = smtp_from
|
| 39 |
+
msg["To"] = to_email
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
with smtplib.SMTP(smtp_host, smtp_port) as server:
|
| 43 |
+
server.starttls()
|
| 44 |
+
if smtp_username and smtp_password:
|
| 45 |
+
server.login(smtp_username, smtp_password)
|
| 46 |
+
server.sendmail(smtp_from, [to_email], msg.as_string())
|
| 47 |
+
print(f"[email_service] Sent email to {to_email}")
|
| 48 |
+
except Exception as e:
|
| 49 |
+
# We don't want email issues to break the app
|
| 50 |
+
print(f"[email_service] Failed to send email to {to_email}: {e}")
|