For HTML email images, use an API approach that generates thumbnails at upload and applies format and byte size limits before sending. For a healthtech application sending appointment reminders, the deciding constraint is whether an image is ready before the message leaves; a transformation triggered by the recipient opening an email puts that work on a path the application cannot schedule.
TL;DR: Use a small, predetermined set of JPEG or PNG derivatives, enforce a byte ceiling on each finished file and a separate budget across the message's images, and reserve on-demand rendering for previews that can tolerate waiting. These are proposed application policies, not universal email-client limits.
This note treats a Node.js API as the upload coordinator and uses Python for the worker contract. The example asset is a clinic's appointment-preparation illustration, with no patient identifiers in its filename or pixels. Clinical photographs need a separate decision about whether they belong in an email at all.
How should an API enforce format limits for HTML email images?
The key invariant is straightforward: a sendable asset has a complete manifest pointing to validated derivative bytes.
An accepted upload is an earlier state.
Conflating those states creates the partial-publication failure mode: the API acknowledges a source object, a sender constructs an email immediately, and the derivative is still being generated. Returning an upload identifier should therefore tell the caller that intake succeeded; readiness needs its own state. Consider a proposed two-variant job whose worker writes the narrow image and then stops before writing the wider image: if the sender treats the existence of either object as completion, template selection determines whether a half-finished job appears successful. The manifest must represent the entire required set, with no partial-ready interpretation. A retry can safely finish the set only if object writes and the manifest commit have explicit idempotency contracts; otherwise a retry merely repeats the ambiguity with a different execution order.
A second invariant ties the manifest to one immutable source revision and one transformation policy revision. A change in crop, encoder settings, or accepted formats creates a new derivative identity. Reusing a mutable object name makes it difficult to establish which bytes a queued message will reference, especially when the source changes between scheduling and sending. Treat the manifest as a record of exact artifacts, not a promise to perform future work.
Bytes matter twice. An upload-size limit bounds intake; it does not establish the size of the encoded thumbnail. Conversely, a small compressed source does not establish an acceptable decoded pixel count. The proposed worker rejects sources outside a configured pixel budget before unrestricted decoding, checks encoded output afterward, and publishes readiness only when every required variant passes. Decoder resource limits still belong in the worker's execution environment; a function argument alone cannot constrain a decoder.
Publication is separate.
The storage adapter must define what a successful write means, when a subsequent read can retrieve the exact object, and how the manifest commit prevents competing workers from overwriting an existing result. No durability or consistency guarantee follows from calling something object storage. If the adapter cannot establish those properties, the readiness invariant has not been implemented.
Decision: bound the work before message assembly
The format guide in References describes JPEG as suitable for lossy compression of still images and PNG as a lossless format supporting transparency. Those properties support a conservative starting policy: JPEG for photographic appointment-preparation imagery, PNG for diagrams that need transparency or lossless reproduction. That is a format-selection rationale, not proof that every mailbox will render a particular file identically. Target-client testing remains necessary, and responsive layout must remain usable when an image is unavailable.
Use two illustrative widths, 320 and 640 pixels, while preserving aspect ratio and preventing enlargement. These are design choices for the example, not standard email widths. A narrow card and a wider rendering can share the same source revision; the message template selects a known artifact for its layout rather than assuming that a recipient's client will negotiate the correct variant.
For an example policy, cap each derivative at 150,000 encoded bytes and the selected images in one message at 300,000 bytes. Define those numbers as decimal bytes in configuration and instrumentation. They are deliberately explicit, adjustable acceptance criteria; neither the format guide nor this note establishes a universal maximum email image size. Count the files actually referenced by the message, not every sibling derivative stored for other templates.
| Processing policy | Work on the recipient request path | Storage consequence | Failure boundary and suitable use |
|---|---|---|---|
| Predetermined variants at upload | Retrieval of a completed artifact | Stores variants even if no email uses them | Encoding failure blocks readiness; suitable for fixed reminder templates |
| Transformation on demand | First request may require decoding and encoding | Can avoid generating unused variants | Render failure reaches the image request; suitable for previews with an explicit loading state |
| Upload baseline with later variants | Known baseline is already available | Adds artifacts when layouts need them | Additional variants need their own readiness state; suitable when template requirements expand |
Precomputation trades extra stored artifacts and upload-side work for an inspectable send boundary. The trade-off is additional storage and processing for variants that may never be requested. This approach is not suitable for an unbounded set of exploratory crop sizes; use on-demand previews for that workload. The limitation is deliberate: upload processing bounds required email artifacts, while preview processing serves changing layout experiments.
Keep that boundary explicit.
Measure derivative count and utilization before expanding the policy; storage consumption is part of the decision, even without making unit prices the argument.
Critical path: encode, validate, then publish the manifest
The following Python example is an orchestration contract, not a decoder implementation. Its adapters must supply bounded decoding, metadata removal, immutable writes, and an atomic manifest commit; the coordinator cannot create those properties by naming methods after them. Assume intake has already recorded an immutable source revision and a retryable job.
from dataclasses import dataclass from hashlib import sha256 @dataclass(frozen=True) class Policy: revision: str = "email-v1" widths: tuple[int, ...] = (320, 640) max_pixels: int = 12_000_000 max_derivative_bytes: int = 150_000 def prepare_email_images(source_revision, source, codec, store, policy): image = codec.decode_bounded( source, max_pixels=policy.max_pixels ) output_format = codec.choose_jpeg_or_png(image) entries = [] for width in policy.widths: payload = codec.encode_thumbnail( image, width=width, allow_upscale=False, output_format=output_format, strip_metadata=True, ) if not payload or len(payload) > policy.max_derivative_bytes: raise ValueError("Derivative is empty or exceeds the byte policy") digest = sha256(payload).hexdigest() key = f"derivatives/{digest}" store.put_immutable(key, payload, output_format=output_format) entries.append({ "requested_width": width, "key": key, "sha256": digest, "bytes": len(payload), "format": output_format, }) return store.commit_manifest_once( source_revision=source_revision, policy_revision=policy.revision, entries=entries, ) def check_message_budget(selected_entries, max_bytes=300_000): if sum(entry["bytes"] for entry in selected_entries) > max_bytes: raise ValueError("Selected images exceed the message byte policy") The hash identifies the encoded bytes.
It does not establish authorization, retention, or backup durability. The adapter must reject an incompatible existing manifest rather than silently return a different set of entries, and it must ensure that successfully committed references are readable under the delivery path's access rules. The sender then selects entries from that manifest and runs the aggregate budget check before rendering the message.
Reject oversize output explicitly.
A bounded retry with a separately specified encoder policy could be reasonable, but silently reducing quality until a file fits makes visual acceptance difficult to reproduce. For a diagram containing appointment instructions, a passing byte count is insufficient: the rendered text must still be legible in the actual template. Preserve useful instructions as message text so a blocked or missing image does not carry the entire appointment instruction.
Failure boundaries, deployment, and evidence
A worker can stop after writing the first derivative and before committing the manifest. Under this design, that leaves an unreferenced artifact rather than a partly ready image set. Retrying the same immutable writes should be safe under the adapter contract; reclaiming abandoned artifacts requires a retention window that accounts for active jobs and manifest references. An unreferenced object is a cleanup candidate only after those checks, not merely because it is old.
Another failure is revision confusion: a template expects a newly added width while the sender still reads a manifest produced by the previous policy. Deploy a new policy revision alongside its workers, generate the required artifacts, and enable the dependent template only after readiness can be demonstrated. Keep older manifests while scheduled messages still need them. Deleting them during a rollout turns a successful processing migration into a delivery failure.
The verification set should exercise a valid photograph, a transparent diagram, an unsupported input, an excessive pixel count, an encoded derivative above the ceiling, and a worker interruption between writes and commit. Also test concurrent retries and deletion while a message is queued. These are proposed tests, not reported results. Client rendering evidence must come from the mailbox and device combinations the team actually supports; format documentation alone cannot supply it.
Record intake-to-ready latency, rejection reason, derivative byte count, orphan cleanup volume, and delivery-path retrieval failures. Avoid putting original filenames or image contents into those events. A useful operational distinction is whether an image never became ready or became ready and later became unreadable, because those failures implicate different boundaries and need different owners.
There is an access decision too. A broadly retrievable appointment illustration and an image restricted to an authenticated patient session have different delivery requirements. Establish those requirements before choosing image URLs; a URL's expiration and an artifact's retention policy must be evaluated against when the email may be opened. Metadata stripping does not remove sensitive information already visible in the pixels.
Rejected option: defer every transformation until the first open
Rendering everything on demand is rejected for the reminder's required image set because it makes image readiness depend on a later request, outside the send transaction's control. It also leaves the sender unable to check the final encoded bytes unless the same transformation has already run elsewhere. The proposed upload policy makes both facts observable before assembly.
On-demand processing still has a valid use case: an internal preview tool exploring many crop sizes, where the interface can expose a pending render and retry a failed request. Promote an approved preview into a completed, validated artifact before referencing it from a reminder.
For this healthtech workflow, accept a thumbnail into the send path only when its format, exact byte count, source revision, and access lifetime are established. Keep the required variant set small. Expand it when a real template requires another shape and the team can demonstrate that it preserves the same publication guarantees.
References
- MDN Web Docs, Image file type and format guide: https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types