Recipe 9.3 · Python
Attachments and Inline Images
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
Reports, invoices and statements go out as attachments. The usual code reads the whole file into a byte array, attaches it with a name built from user data, never disposes the stream, and has no idea how large the message has become until the relay rejects it with a 552 error at month end. Logos are attached as regular files, so they show up as a paper clip instead of in the message.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Every file in the folder goes out, including the ones another process is still writing, and file handles stay open until garbage collection runs.
Requirements: Python 3.12+. Standard library only, nothing to install. · Needs at run time: an SMTP server. The module loads without them; calling the code does not work without them.
"""Attaching every file in a folder with no size limit
Source: ImproveCode, Chapter 9, Recipe 9.3 "Attachments and Inline Images"
Section: The way it's often written
Book page: 192 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
smtplib + EmailMessage.add_attachment replace MailMessage/Attachment.
"""
import mimetypes
import os
import smtplib
from email.message import EmailMessage
def send_reports(client: smtplib.SMTP, sender: str, to: str, subject: str,
body: str, report_folder: str) -> None:
msg = EmailMessage()
msg["From"], msg["To"], msg["Subject"] = sender, to, subject
msg.set_content(body)
for name in os.listdir(report_folder):
path = os.path.join(report_folder, name)
if not os.path.isfile(path):
continue
ctype = mimetypes.guess_type(path)[0] or "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
with open(path, "rb") as f:
msg.add_attachment(f.read(), maintype=maintype, subtype=subtype,
filename=name)
client.send_message(msg)
The improved recipe
A composer class wraps MimeKit's BodyBuilder. It tracks the total attachment size against a limit, guesses the media type from the file name, and supports inline images referenced from the HTML by content ID.
A usage snippet showing a statement with a logo and a PDF:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Fluent e-mail composer with attachment budget and inline CID images
Source: ImproveCode, Chapter 9, Recipe 9.3 "Attachments and Inline Images"
Section: The improved recipe
Book page: 193-194 -- original C# listing
Converted from C# to Python.
email.message.EmailMessage replaces MimeKit's BodyBuilder (related parts for
LinkedResources); mimetypes replaces MimeTypes; make_msgid replaces MimeUtils.
"""
import asyncio
import mimetypes
import os
from email.message import EmailMessage
from email.utils import make_msgid
from typing import BinaryIO
class EmailComposer:
def __init__(self, max_attachment_bytes: int = 10 * 1024 * 1024) -> None:
if max_attachment_bytes <= 0:
raise ValueError("max_attachment_bytes must be greater than zero.")
self._max_attachment_bytes = max_attachment_bytes
self._attachment_bytes = 0
self._html: str | None = None
self._text: str | None = None
self._attachments: list[tuple[str, bytes, str]] = []
self._inline: list[tuple[str, bytes, str, str]] = []
def html(self, html: str) -> "EmailComposer":
self._html = html
return self
def text(self, text: str) -> "EmailComposer":
self._text = text
return self
async def attach_async(self, file_name: str,
content: BinaryIO) -> "EmailComposer":
if not file_name or not file_name.strip():
raise ValueError("file_name")
if content is None:
raise TypeError("content must not be None.")
data = await asyncio.to_thread(content.read)
self._reserve(len(data))
ctype = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
self._attachments.append((os.path.basename(file_name), data, ctype))
return self
def add_inline_image(self, file_name: str, data: bytes) -> str:
if not file_name or not file_name.strip():
raise ValueError("file_name")
if data is None:
raise TypeError("data must not be None.")
self._reserve(len(data))
content_id = make_msgid()[1:-1] # strip the angle brackets
ctype = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
self._inline.append((os.path.basename(file_name), data, ctype, content_id))
return "cid:" + content_id
def build(self, to: str, subject: str) -> EmailMessage:
if to is None:
raise TypeError("to must not be None.")
message = EmailMessage()
message["To"] = to
message["Subject"] = subject
message.set_content(self._text or "")
if self._html is not None:
message.add_alternative(self._html, subtype="html")
html_part = message.get_payload()[-1]
for name, data, ctype, cid in self._inline:
maintype, subtype = ctype.split("/", 1)
html_part.add_related(data, maintype=maintype, subtype=subtype,
cid=f"<{cid}>", filename=name)
for name, data, ctype in self._attachments:
maintype, subtype = ctype.split("/", 1)
message.add_attachment(data, maintype=maintype, subtype=subtype,
filename=name)
return message
def _reserve(self, count: int) -> None:
if self._attachment_bytes + count > self._max_attachment_bytes:
raise RuntimeError(
f"Attachments exceed {self._max_attachment_bytes:,} bytes. "
"Send a download link instead.")
self._attachment_bytes += count
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Composing a statement e-mail with an inline logo and PDF attachment
Source: ImproveCode, Chapter 9, Recipe 9.3 "Attachments and Inline Images"
Section: The improved recipe
Book page: 194 -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in an async function; file reads go through asyncio.to_thread
in place of File.ReadAllBytesAsync.
"""
import asyncio
from pathlib import Path
from p185_r9_1_async_smtp_email_sender import EmailSender
from p193_r9_3_email_composer_attachments_inline import EmailComposer
async def send_june_statement(sender: EmailSender, to: str, logo_path: str,
statement_path: str) -> None:
composer = EmailComposer()
logo = composer.add_inline_image(
"logo.png", await asyncio.to_thread(Path(logo_path).read_bytes))
(composer.html(f'<img src="{logo}" alt="Logo"><p>Attached.</p>')
.text("Your statement is attached."))
with open(statement_path, "rb") as pdf:
await composer.attach_async("Statement-2025-06.pdf", pdf)
await sender.send_async(composer.build(to, "June statement"))
How it works
AttachAsync copies the caller's stream into a MemoryStream that the message owns. That makes the lifetime simple: the caller can dispose its file stream as soon as the call returns, and the message can be sent, retried or written to disk later without a closed-stream surprise. The size check runs after the copy, against the real byte count, rather than trusting Stream.Length, which non-seekable streams do not support.
MimeTypes.GetMimeType maps the extension to a media type (application/pdf, image/png) and falls back to application/octet-stream. MimeKit encodes the attachment as base64 and the file name with RFC 2231 encoding, so names with accents or non-Latin characters arrive intact.
AddInlineImage adds the image to LinkedResources and gives it a content ID. BodyBuilder then produces a multipart/related part, and the HTML refers to the image as cid:.... Mail clients show it in place without a download prompt and without a call to an external server, which is also kinder to privacy.
Path.GetFileName strips any folder from the attachment name. A name such as ..\..\report.pdf would not hurt the sender, but it can confuse the receiving client and it leaks your folder structure.
Variations and pitfalls
- Base64 adds about a third. A 10 MB file becomes roughly 13.5 MB on the wire. Many relays and mailbox providers cap messages somewhere between 10 MB and 35 MB. Above a few megabytes, send a time-limited download link instead.
- Files still being written. When attaching output from another process, wait for it to finish, or have that process write atomically (Recipe 10.2) so a half-written file is never visible.
- Sensitive attachments. E-mail is not a secure channel. For payroll, medical or banking documents, send a link to an authenticated portal, not the document.
- Generated content. You don't need a file at all. Attach a
MemoryStreamfrom the CSV, Excel or PDF writers in Chapter 11 directly.