Skip to content

common_reports.emails.composer

The MIME composer — an EmailMessage in, a wire-ready MIME message out.

build_message is the EXACT reproduction of AlgoReports’ reporter.generate_email MIME assembly (build-spec §1.6 / §3.8):

msg = MIMEMultipart() # multipart/mixed (NOT alternative)
msg['From'] = <from-addr>
msg['Subject'] = subject
msg['Message-ID'] = make_msgid(domain=<from user-domain>)
msg['Date'] = formatdate(localtime=True)
# NO 'To' header — recipients are supplied only at send time (to_addrs=)
body str -> MIMEText(html, 'html')
body dict -> per key MIMEText(f'<h1>{k}</h1><h2>{v}</h2>', 'html')
attachments -> MIMEApplication + 'Content-Disposition: attachment; filename=...'
trailer (when attachments) -> MIMEText('<h2>The interactive HTML ...</h2>', 'html')

That default output is pinned byte-for-byte (tests/emails/golden). Additive, opt-in structure on top of it:

text given -> multipart/alternative(text/plain, text/html)
inline attachments -> multipart/related(body, image parts with Content-ID)
typed attachments -> the declared maintype/subtype (default octet-stream)
disclose_recipients -> visible To/Cc headers (default: private delivery)

resolve_attachments reproduces the bool / str-dir / str-prefix / list spec (in deterministic name order). Pure: no I/O beyond reading attachment files.

Functions

build_message

def build_message(msg: EmailMessage, from_addr: str, body: Union[str, dict, None] = None, from_name: Optional[str] = None, attachment_note: Union[str, object, None] = _DEFAULT_NOTE) -> MIMEMultipart

Assemble the multipart/mixed MIME message (EXACT AlgoReports parity).

Args: msg: the frozen :class:EmailMessage (subject, html, attachments, extra headers, optional reply_to / text). from_addr: the resolved From address (Message-ID domain is derived from its user-domain via make_msgid). body: optional override — a str (one html part) or a dict (per-key <h1>{k}</h1><h2>{v}</h2> parts). When None, msg.html / msg.text drive the body. from_name: optional display name — when set, the From header becomes "From Name" <from_addr>. The Message-ID domain still derives from the bare from_addr, so display names never corrupt it. attachment_note: HTML appended after file attachments; defaults to the AlgoReports trailer, None omits it.

Returns: A MIMEMultipart() (multipart/mixed) ready for send_message(mime, to_addrs=recipients).

resolve_attachments

def resolve_attachments(attachments: Union[bool, str, list, tuple, None], cwd: Optional[str] = None) -> list[Attachment]

Reproduce the AlgoReports attachment-resolution spec (build-spec §1.6).

  • True -> every *.html in the current working directory.
  • str (a dir) -> every *.html in that directory.
  • str (a prefix) -> *.html in cwd whose name starts with the prefix.
  • list / tuple-> each entry as a path (absolute or cwd-relative), skipping any that don’t exist.
  • falsy -> no attachments.

Returns a list of :class:Attachment (path-backed).