28 lines
851 B
Python
28 lines
851 B
Python
|
|
import os
|
|||
|
|
import smtplib
|
|||
|
|
from email.header import Header
|
|||
|
|
from email.mime.text import MIMEText
|
|||
|
|
|
|||
|
|
|
|||
|
|
def send_email(subject, message, to_email):
|
|||
|
|
smtp_server = os.getenv("SMTP_HOST")
|
|||
|
|
smtp_port = int(os.getenv("SMTP_PORT", "25"))
|
|||
|
|
smtp_user = os.getenv("SMTP_USER")
|
|||
|
|
smtp_password = os.getenv("SMTP_PASSWORD")
|
|||
|
|
|
|||
|
|
if not smtp_server or not smtp_user or not smtp_password:
|
|||
|
|
raise ValueError("SMTP 配置缺失:需要 SMTP_HOST/SMTP_USER/SMTP_PASSWORD(可选 SMTP_PORT)")
|
|||
|
|
|
|||
|
|
msg = MIMEText(message, "plain", "utf-8")
|
|||
|
|
msg["From"] = Header(smtp_user)
|
|||
|
|
msg["To"] = Header(to_email)
|
|||
|
|
msg["Subject"] = Header(subject)
|
|||
|
|
|
|||
|
|
server = smtplib.SMTP(smtp_server, smtp_port)
|
|||
|
|
try:
|
|||
|
|
server.login(smtp_user, smtp_password)
|
|||
|
|
server.sendmail(smtp_user, [to_email], msg.as_string())
|
|||
|
|
finally:
|
|||
|
|
server.quit()
|
|||
|
|
|