|
| 1 | +"""Send email via SMTP for the ``AC_send_email`` action step. |
| 2 | +
|
| 3 | +Dependency-free (stdlib ``smtplib`` + ``email``). Parameters are grouped |
| 4 | +into two dicts so the action stays JSON-friendly and within the project's |
| 5 | +argument-count limit: |
| 6 | +
|
| 7 | +* ``message`` — ``{sender, to, subject, body, cc?, html?, attachments?}`` |
| 8 | +* ``smtp`` — ``{host, port?, username?, password?, use_tls?, use_ssl?, |
| 9 | + timeout?}`` |
| 10 | +
|
| 11 | +Security: TLS is on by default (STARTTLS on 587, or implicit SSL when |
| 12 | +``use_ssl`` is set), the connection uses a verified default SSL context, |
| 13 | +every call has an explicit timeout, and credentials are never logged. |
| 14 | +Imports no ``PySide6`` so it stays fully headless. |
| 15 | +""" |
| 16 | +import mimetypes |
| 17 | +import os |
| 18 | +import smtplib |
| 19 | +import ssl |
| 20 | +from email.message import EmailMessage |
| 21 | +from typing import Any, Dict, List, Mapping, Optional |
| 22 | + |
| 23 | + |
| 24 | +def _as_list(value: Any) -> List[str]: |
| 25 | + """Normalise a string / iterable of addresses into a list of strings.""" |
| 26 | + if value is None: |
| 27 | + return [] |
| 28 | + if isinstance(value, str): |
| 29 | + return [value] |
| 30 | + return [str(item) for item in value] |
| 31 | + |
| 32 | + |
| 33 | +def _attach_files(mime: EmailMessage, attachments: Any) -> None: |
| 34 | + """Attach each file path in ``attachments`` to ``mime``.""" |
| 35 | + for raw in attachments or []: |
| 36 | + path = os.path.realpath(str(raw)) |
| 37 | + if not os.path.isfile(path): |
| 38 | + raise FileNotFoundError(f"attachment not found: {raw}") |
| 39 | + ctype, _ = mimetypes.guess_type(path) |
| 40 | + maintype, subtype = ( |
| 41 | + ctype.split("/", 1) if ctype else ("application", "octet-stream")) |
| 42 | + with open(path, "rb") as handle: |
| 43 | + mime.add_attachment(handle.read(), maintype=maintype, |
| 44 | + subtype=subtype, filename=os.path.basename(path)) |
| 45 | + |
| 46 | + |
| 47 | +def _build_message(message: Mapping[str, Any]) -> EmailMessage: |
| 48 | + """Assemble an :class:`EmailMessage` from the ``message`` spec.""" |
| 49 | + sender = message.get("sender") or message.get("from") |
| 50 | + recipients = _as_list(message.get("to")) |
| 51 | + if not sender or not recipients: |
| 52 | + raise ValueError("email requires 'sender' and at least one 'to'") |
| 53 | + mime = EmailMessage() |
| 54 | + mime["From"] = str(sender) |
| 55 | + mime["To"] = ", ".join(recipients) |
| 56 | + cc = _as_list(message.get("cc")) |
| 57 | + if cc: |
| 58 | + mime["Cc"] = ", ".join(cc) |
| 59 | + mime["Subject"] = str(message.get("subject", "")) |
| 60 | + body = str(message.get("body", "")) |
| 61 | + mime.set_content(body, subtype="html" if message.get("html") else "plain") |
| 62 | + _attach_files(mime, message.get("attachments")) |
| 63 | + return mime |
| 64 | + |
| 65 | + |
| 66 | +def _login_send(server: smtplib.SMTP, username: Optional[str], |
| 67 | + password: Optional[str], mime: EmailMessage) -> None: |
| 68 | + """Authenticate (when credentials are given) and send the message.""" |
| 69 | + if username and password: |
| 70 | + server.login(username, password) |
| 71 | + server.send_message(mime) |
| 72 | + |
| 73 | + |
| 74 | +def _deliver(mime: EmailMessage, smtp: Mapping[str, Any]) -> None: |
| 75 | + """Open an SMTP(S) connection per ``smtp`` config and send ``mime``.""" |
| 76 | + host = smtp.get("host") |
| 77 | + if not host: |
| 78 | + raise ValueError("smtp 'host' is required") |
| 79 | + port = int(smtp.get("port", 587)) |
| 80 | + timeout = float(smtp.get("timeout", 30.0)) |
| 81 | + username, password = smtp.get("username"), smtp.get("password") |
| 82 | + if bool(smtp.get("use_ssl", False)): |
| 83 | + context = ssl.create_default_context() |
| 84 | + with smtplib.SMTP_SSL(str(host), port, timeout=timeout, |
| 85 | + context=context) as server: |
| 86 | + _login_send(server, username, password, mime) |
| 87 | + return |
| 88 | + with smtplib.SMTP(str(host), port, timeout=timeout) as server: |
| 89 | + if bool(smtp.get("use_tls", True)): |
| 90 | + server.starttls(context=ssl.create_default_context()) |
| 91 | + _login_send(server, username, password, mime) |
| 92 | + |
| 93 | + |
| 94 | +def send_email(message: Mapping[str, Any], |
| 95 | + smtp: Mapping[str, Any]) -> Dict[str, Any]: |
| 96 | + """Send an email and return a small result dict. |
| 97 | +
|
| 98 | + :param message: ``{sender, to, subject, body, cc?, html?, attachments?}``. |
| 99 | + :param smtp: ``{host, port?, username?, password?, use_tls?, use_ssl?, |
| 100 | + timeout?}``; TLS is enabled by default. |
| 101 | + """ |
| 102 | + mime = _build_message(message) |
| 103 | + _deliver(mime, smtp) |
| 104 | + return {"sent": True, "to": mime["To"], "subject": mime["Subject"]} |
0 commit comments