Skip to content
Tinbox

tutorials

Handle inbound email attachments safely without getting owned

September 7, 2026

#email-attachments#cloudflare-workers#security#cloudflare-r2#tutorial
An inbox connected to a tool through a keyed access gate.

You pointed Cloudflare Email Routing at a Worker, you are happily parsing subjects and bodies, and then a message arrives carrying invoice.pdf that is actually a Windows executable and a 180 MB zip. Here is how to take attachments without taking damage.

Inbound attachments are the part of an email pipeline most likely to hurt you. The body is a known quantity: text and HTML, small, easy to sanitize. Attachments are arbitrary attacker-controlled bytes with attacker-controlled names, and a naive handler does at least three dangerous things: it buffers the whole message into memory before checking the size, it trusts the declared content type, and it stores or re-serves files in a way that lets a payload reach a human or a parser. This walkthrough builds a safe inbound-attachment handler on Cloudflare Workers by hand, with the failure modes shown, then points at where Tinbox already does this so you can skip the wiring.

If you have not parsed the MIME yet, start with parsing raw MIME email in JavaScript and the inbound email webhook on Workers. This article picks up once you can already walk the parts. For the wiring that gets a message to your Worker in the first place, see the steps to receive inbound email on your own Cloudflare account.

What does safe inbound attachment handling actually require?

Safe handling is five checks in order, each gating the next: size, extraction, real type, scan, storage. Skipping any one of them is where people get owned. The order matters because each step assumes the previous one ran: you cannot sniff bytes you refused to buffer, and you should not scan bytes you already rejected on type. Here is the full pipeline before we build each piece.

StepWhat it defends againstFailure if you skip it
Size cap (before buffering)Memory exhaustion, storage blowupsA 200 MB message OOMs the Worker
Extract partsn/a (mechanics)You cannot inspect what you did not isolate
Sniff real typeSpoofed extensions and Content-Typeinvoice.pdf runs as an executable
Allowlist + quarantineDangerous file typesYou store and re-serve malware
AV scanKnown malware in allowed typesA weaponized real PDF reaches a user
Private R2 + safe servePublic exposure, inline executionA browser executes an SVG or HTML attachment

The rest of this is each row, in code.

How do I cap attachment size before it blows up memory?

Enforce the ceiling while you read the stream, not after, because a Worker has a hard memory limit and reading a hostile 200 MB message into a single buffer can kill the isolate before you ever get to measure it. Cloudflare Email Routing hands your Worker a ReadableStream of the raw RFC 5322 message. The safe move is to drain it through a counter and abort the moment you cross your limit.

const MAX_MESSAGE_BYTES = 25 * 1024 * 1024; // 25 MB total, matching common provider caps

async function readRawCapped(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
  const reader = stream.getReader();
  const chunks: Uint8Array[] = [];
  let total = 0;

  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    total += value.byteLength;
    if (total > MAX_MESSAGE_BYTES) {
      await reader.cancel();
      throw new MessageTooLargeError(total);
    }
    chunks.push(value);
  }

  const out = new Uint8Array(total);
  let offset = 0;
  for (const c of chunks) {
    out.set(c, offset);
    offset += c.byteLength;
  }
  return out;
}

The cheap mistake looks like this and you will not feel it until a real attacker shows up:

// DON'T: reads the whole hostile message before you can react
const raw = new Uint8Array(await new Response(message.raw).arrayBuffer());
if (raw.byteLength > MAX_MESSAGE_BYTES) throw new Error("too big"); // too late

By the time that if runs, the bytes are already resident. The capped reader rejects oversize input mid-stream and frees you to set a tighter per-attachment limit too (most legitimate inbound files are well under 25 MB; a 25 MB single image is suspicious on its own).

How do I extract attachment parts from a parsed email?

Walk the MIME tree and collect every leaf part whose Content-Disposition is attachment, capturing its declared filename, declared content type, and decoded bytes. Inline parts (Content-Disposition: inline, usually images referenced by cid:) are a separate concern; here we want the explicit attachments. Assuming a parser that yields flat leaf parts (see the MIME parsing walkthrough for one you can write in about 120 lines):

type RawAttachment = {
  declaredName: string;
  declaredType: string;
  bytes: Uint8Array;
};

function collectAttachments(parts: MimePart[]): RawAttachment[] {
  const out: RawAttachment[] = [];
  for (const part of parts) {
    const disp = (part.headers["content-disposition"] ?? "").toLowerCase();
    if (!disp.startsWith("attachment")) continue;
    out.push({
      declaredName: filenameFromDisposition(disp) ?? "unnamed",
      declaredType: (part.headers["content-type"] ?? "application/octet-stream")
        .split(";")[0]
        .trim()
        .toLowerCase(),
      bytes: part.decodedBytes, // already base64/quoted-printable decoded
    });
  }
  return out;
}

Everything in declaredName and declaredType is a string the sender chose. We capture it for the record, but we do not let it decide anything. That decision is the next step.

Why can't I trust the filename or the declared Content-Type?

Because both are copied verbatim from an email an attacker fully controls, so a file named invoice.pdf with Content-Type: application/pdf can be a .exe, and a part labeled image/png can be HTML with an embedded script. The only authority on what a file is comes from its own bytes: the magic number at the start of the content. Sniff it.

type SniffResult = { type: string; ext: string } | { type: "unknown"; ext: "" };

function sniffType(bytes: Uint8Array): SniffResult {
  const b = bytes;
  const starts = (...sig: number[]) => sig.every((v, i) => b[i] === v);

  if (starts(0x25, 0x50, 0x44, 0x46)) return { type: "application/pdf", ext: "pdf" }; // %PDF
  if (starts(0x89, 0x50, 0x4e, 0x47)) return { type: "image/png", ext: "png" };
  if (starts(0xff, 0xd8, 0xff)) return { type: "image/jpeg", ext: "jpg" };
  if (starts(0x47, 0x49, 0x46, 0x38)) return { type: "image/gif", ext: "gif" };

  // Dangerous: executables and containers
  if (starts(0x4d, 0x5a)) return { type: "application/x-dosexec", ext: "exe" }; // MZ (PE/Windows)
  if (starts(0x7f, 0x45, 0x4c, 0x46)) return { type: "application/x-elf", ext: "elf" }; // ELF (Linux)
  if (starts(0xcf, 0xfa, 0xed, 0xfe)) return { type: "application/x-mach-binary", ext: "macho" };
  if (starts(0x50, 0x4b, 0x03, 0x04)) return { type: "application/zip", ext: "zip" }; // also docx/xlsm

  return { type: "unknown", ext: "" };
}

Note the trap in the last entry: modern Office files (.docx, .xlsm, .pptx) are zip containers, so PK\x03\x04 is both a plain zip and a macro-enabled spreadsheet. Magic bytes get you to "this is a zip," not "this is safe." To distinguish a benign .docx from a macro-bearing .xlsm you have to look inside the zip for a vbaProject.bin entry, which is more than most pipelines do. The pragmatic answer is to treat all Office-zip files as elevated risk and lean on the allowlist plus scanner below rather than trying to fully classify them yourself.

Now reconcile. If the declared type says application/pdf but the bytes say application/x-dosexec, that mismatch is itself a strong signal of an attack and should push the file straight to quarantine.

What attachment types should I block?

Block or quarantine anything executable, scriptable, or commonly used as a malware container, and accept only an explicit allowlist of types you actually expect. An allowlist is safer than a blocklist because new dangerous extensions appear faster than you will update a denylist.

const ALLOWED_TYPES = new Set([
  "application/pdf",
  "image/png",
  "image/jpeg",
  "image/gif",
  "image/webp",
  "text/plain",
  "text/csv",
  // plain (non-macro) Office; still scanned, see below
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
]);

const ALWAYS_BLOCK = new Set([
  "application/x-dosexec",
  "application/x-elf",
  "application/x-mach-binary",
  "application/x-msdownload",
]);

type Verdict = "accept" | "quarantine" | "reject";

function classify(sniffed: string, declared: string): Verdict {
  if (ALWAYS_BLOCK.has(sniffed)) return "reject";
  if (sniffed === "unknown") return "quarantine";
  if (sniffed !== declared && declared !== "application/octet-stream") {
    return "quarantine"; // type spoofing: bytes disagree with the label
  }
  return ALLOWED_TYPES.has(sniffed) ? "accept" : "quarantine";
}

reject drops the file entirely. quarantine stores it but marks it unavailable for normal download (an admin can release it deliberately). accept proceeds to scanning. The difference between reject and quarantine matters operationally: you almost never want to silently delete a customer's attachment, but you absolutely do not want it one careless click away from a user, so quarantine is the right default for "suspicious but not provably hostile."

Do I need to scan email attachments for malware, and how?

Yes for anything a human will eventually open, and you scan by sending the bytes to an external engine, because the Workers runtime cannot run the native ClamAV daemon or its local Unix-socket protocol. Workers do expose outbound TCP, so a compatible client could reach an allowed remote scanner, but an HTTPS scanning API is the simpler supported integration. Storing bytes in R2 does not execute them, so the Worker itself is not at risk. The risk is the user who downloads the file and the document parser you might run on it. Both sit downstream of storage, so scan before either touches the bytes.

The practical pattern on Cloudflare is to POST the file to a scanning service over HTTPS (a self-hosted ClamAV behind a small HTTP shim, or a commercial scanning API) and store the verdict alongside the metadata.

async function scan(bytes: Uint8Array, env: Env): Promise<"clean" | "infected" | "error"> {
  try {
    const res = await fetch(env.SCANNER_URL, {
      method: "POST",
      headers: { "content-type": "application/octet-stream" },
      body: bytes,
    });
    if (!res.ok) return "error";
    const { status } = (await res.json()) as { status: "clean" | "infected" };
    return status;
  } catch {
    return "error"; // fail closed: treat scanner failure as not-yet-clean
  }
}

Fail closed. If the scanner is unreachable, the file is error, not clean, and it lands in quarantine until the scan can complete. The alternative (treating a scanner timeout as a pass) is exactly the gap an attacker waits for.

How do I store inbound attachments safely in R2?

Write the raw bytes to a private R2 bucket keyed by their SHA-256 hash, keep only metadata in D1, and serve downloads through an authenticated Worker with Content-Disposition: attachment. Never make the bucket public and never serve an attachment inline. Content addressing also dedupes: the same PDF forwarded to ten inboxes is stored once. This is the same storage split covered in depth in storing email attachments in Cloudflare R2; attachment storage is only one of the smart ways to use Cloudflare R2 in an email stack. Here is the security-relevant version.

async function storeAttachment(att: RawAttachment, verdict: Verdict, env: Env) {
  const digest = await crypto.subtle.digest("SHA-256", att.bytes);
  const key = [...new Uint8Array(digest)]
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");

  // Only put bytes for files we accepted or quarantined; rejected files are dropped.
  if (verdict !== "reject") {
    const existing = await env.ATTACHMENTS.head(key);
    if (!existing) {
      await env.ATTACHMENTS.put(key, att.bytes, {
        // Store an inert type so nothing downstream is tempted to treat it as runnable.
        httpMetadata: { contentType: "application/octet-stream" },
      });
    }
  }

  await env.DB.prepare(
    `INSERT INTO attachments (r2_key, filename, sniffed_type, size_bytes, verdict)
     VALUES (?, ?, ?, ?, ?)`,
  )
    .bind(verdict === "reject" ? null : key, att.declaredName, sniffType(att.bytes).type, att.bytes.byteLength, verdict)
    .run();
}

The download route is where the last mistake hides. Serve it like this:

// GET /attachments/:id  (behind your auth check)
const obj = await env.ATTACHMENTS.get(key);
return new Response(obj.body, {
  headers: {
    // Force download, never render in the browser.
    "content-disposition": `attachment; filename="${safeFilename(name)}"`,
    "content-type": "application/octet-stream",
    "x-content-type-options": "nosniff",
    "content-security-policy": "default-src 'none'; sandbox",
  },
});

Content-Disposition: attachment plus application/octet-stream plus nosniff stops a browser from rendering an HTML or SVG attachment as a live document. Sanitize the filename in the header too (strip quotes, CR, and LF) so a crafted name cannot inject extra headers. Serving an inbound attachment inline from a path on your own origin is how a stored-XSS payload becomes a same-origin one.

Putting the pipeline together

The full inbound handler chains the steps and lets each verdict gate the next.

export default {
  async email(message: ForwardableEmailMessage, env: Env) {
    let raw: Uint8Array;
    try {
      raw = await readRawCapped(message.raw);
    } catch (e) {
      if (e instanceof MessageTooLargeError) {
        message.setReject("Message exceeds size limit");
        return;
      }
      throw e;
    }

    const parts = parseMime(raw); // your MIME parser
    for (const att of collectAttachments(parts)) {
      const sniffed = sniffType(att.bytes).type;
      let verdict = classify(sniffed, att.declaredType);

      if (verdict === "accept") {
        const scan = await scanFile(att.bytes, env);
        if (scan !== "clean") verdict = "quarantine";
      }

      await storeAttachment(att, verdict, env);
    }
  },
};

Five checks, in order, fail-closed at every gate. That is the whole defensible design. None of it is exotic, but every line is one that a naive handler skips, and each skipped line is a documented way to get owned.

Or skip the wiring: how Tinbox handles this

Tinbox runs this exact pipeline on your own Cloudflare account so you do not assemble it yourself. On inbound mail it enforces a size cap before buffering, extracts attachment parts, records the real sniffed type next to the declared one, and writes the bytes to a private R2 bucket keyed by content hash, with filename, type, size, and verdict in D1. Downloads go through an authenticated Worker route with Content-Disposition: attachment and a locked-down CSP, exactly as above. You can plug your own type allowlist and an external scanner into the interpreter step, the same algorithmic-plus-LLM classification pipeline used elsewhere in the stack.

A few honest caveats so you size it right. Tinbox ships the safe storage and serving by default; the malware scanner is a bring-your-own integration, because a scan engine is infrastructure you have to operate (Workers cannot run ClamAV in-process). And like the rest of Tinbox, this runs per deployed brand and domain on your own account, so the data never leaves your Cloudflare boundary. For how the receiving, storage, and AI-over-inbox pieces fit together, see the Tinbox overview.

Deploy this yourself: npx tinbox init <domain>, then read the inbound and attachments docs to wire your own type allowlist and scanner. You get the size cap, sniffing, private R2 storage, and safe download route out of the box, and you spend your time only on the policy that is specific to your product.

Frequently asked questions

How do I handle inbound email attachments safely?

Treat every attachment as hostile input. Cap the total message size before buffering so a 200 MB email cannot exhaust memory. Sniff the real content type from the file's magic bytes rather than trusting the declared Content-Type or filename extension. Block or quarantine executable and script types, run a malware scan if you can, then store the bytes in a private R2 bucket keyed by their SHA-256 hash, with only metadata in D1. Never serve attachments from a public bucket or with an inline content disposition.

Can you get a virus from an email attachment on a server?

Storing the bytes does not run them, so a Worker that writes an attachment to R2 is not itself infected. The risk is downstream: a user who downloads and opens the file, a thumbnail or document parser you run on it that has its own vulnerabilities, or an attachment you re-serve inline so a browser executes embedded HTML or SVG script. Scan before you let bytes reach a human, and always serve with Content-Disposition: attachment.

Why can't I trust the filename or Content-Type on an attachment?

Both are attacker-controlled strings copied straight from the email. A file named invoice.pdf can be a Windows executable, and a part labeled image/png can be an HTML file with a script payload. Sniff the first few bytes of the actual content (the magic number) to learn the true type, and reconcile it against the declared type before deciding whether to accept, quarantine, or reject the file.

What attachment types should I block from inbound email?

Block or quarantine executables (.exe, .dll, .msi, Mach-O, ELF), scripts (.js, .vbs, .ps1, .sh, .bat, .cmd), Windows shortcuts (.lnk), disk images and archives that commonly carry payloads (.iso, .img, password-protected .zip), and macro-enabled Office files (.docm, .xlsm). Decide on an allowlist of types you actually expect (PDF, images, plain Office docs, CSV) and treat everything else as quarantine-by-default.

How big can an email attachment be, and where do I enforce the limit?

Most providers cap a single message at around 25 MB, but a Worker receiving inbound mail should enforce its own ceiling and do it before it buffers the whole message into memory. Check the raw stream size as you read it and abort once you cross your limit (for example 25 MB total), rather than reading the entire ReadableStream and then measuring, which lets a hostile sender push you toward the Worker memory limit.

Does Tinbox handle inbound attachments safely by default?

Yes. Tinbox runs on your own Cloudflare account and, on inbound mail, enforces a size cap, extracts attachment parts, records their real sniffed type, and writes the bytes to a private R2 bucket keyed by content hash with metadata in D1. Downloads go through an authenticated Worker route with Content-Disposition: attachment. You can layer your own type allowlist and scanning on top via the interpreter pipeline.