mail/app/services/smtp_sender.py
deeily 5024bf9a8d init: full mail stack — phases 0..8 (web client, admin, IMAP/SMTP,
sieve, search, sessions, dramatiq, deploy/install, ELK, monitoring)
2026-04-29 16:30:43 +03:00

77 lines
2.1 KiB
Python

"""SMTP sender using smtplib.
Sends messages to the submission port (587) of docker-mailserver.
"""
import mimetypes
import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate, make_msgid
from email import encoders
from flask import current_app
def send_message(
from_email: str,
password: str,
to_emails: list[str],
cc_emails: list[str],
bcc_emails: list[str],
subject: str,
body_html: str,
body_text: str = "",
important: bool = False,
attachments: list | None = None,
) -> bytes:
host = current_app.config["SMTP_HOST"]
port = int(current_app.config.get("SMTP_PORT", 587))
body_msg = MIMEMultipart("alternative")
if body_text:
body_msg.attach(MIMEText(body_text, "plain", "utf-8"))
body_msg.attach(MIMEText(body_html, "html", "utf-8"))
if attachments:
msg = MIMEMultipart("mixed")
msg.attach(body_msg)
for att in attachments:
filename = att["filename"]
data = att["data"]
ctype, _ = mimetypes.guess_type(filename)
if ctype is None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
part = MIMEBase(maintype, subtype)
part.set_payload(data)
encoders.encode_base64(part)
part.add_header("Content-Disposition", "attachment", filename=filename)
msg.attach(part)
else:
msg = body_msg
msg["From"] = from_email
msg["To"] = ", ".join(to_emails)
if cc_emails:
msg["Cc"] = ", ".join(cc_emails)
msg["Subject"] = subject
msg["Date"] = formatdate()
msg["Message-ID"] = make_msgid()
if important:
msg["X-Priority"] = "1"
msg["Importance"] = "high"
all_recipients = to_emails + cc_emails + bcc_emails
raw = msg.as_bytes()
smtp = smtplib.SMTP(host, port, timeout=15)
try:
smtp.ehlo()
smtp.login(from_email, password)
smtp.sendmail(from_email, all_recipients, raw)
finally:
smtp.quit()
return raw