File size: 1,474 Bytes
9876bd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import os
import smtplib
from email.message import EmailMessage

EMAIL_USER = os.getenv("EMAIL_USER")
# Support EMAIL_PASSWORD as either plain text or base64-encoded string.
# If it's base64-encoded, decode it; otherwise, use the raw value.
_raw_email_password = os.getenv("EMAIL_PASSWORD")
EMAIL_PASSWORD = None
if _raw_email_password:
    # Try base64 decode, fall back to raw string if decode fails or is nonsense
    try:
        import base64 as _b64
        decoded = _b64.b64decode(_raw_email_password).decode()
        # Basic sanity: decoded password should be non-empty
        if decoded:
            EMAIL_PASSWORD = decoded
        else:
            EMAIL_PASSWORD = _raw_email_password
    except Exception:
        EMAIL_PASSWORD = _raw_email_password


def send_email(to_email, subject, body):
    """Send an email using SMTP_SSL (Gmail).



    Reads EMAIL_USER and EMAIL_PASSWORD from environment variables.

    Raises RuntimeError if credentials are not set.

    """
    if not EMAIL_USER or not EMAIL_PASSWORD:
        raise RuntimeError("Email credentials not configured in environment variables")

    msg = EmailMessage()
    msg.set_content(body)
    msg["Subject"] = subject
    msg["From"] = EMAIL_USER
    msg["To"] = to_email

    # Use SMTP_SSL for a secure connection
    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
        smtp.login(EMAIL_USER, EMAIL_PASSWORD)
        smtp.send_message(msg)