> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bosonware.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Attachments

> Attach files to emails with the BosonMail SDK. Supported content types, size limits, multipart transport, and security best practices.

The BosonMail SDK supports file attachments through the `attachments` field in `SendEmailBody`. When attachments are present, the request automatically switches from JSON to `multipart/form-data` transport. The SDK validates attachment count, filename presence, content type, and size limits client-side before sending.

## SendAttachment interface

```typescript theme={null}
interface SendAttachment {
  filename: string;
  content: Blob | Uint8Array | ArrayBuffer;
  contentType?: string;
}
```

**filename** `string` *required*

The name of the file as it appears to the recipient. Must be non-empty.

**content** `Blob | Uint8Array | ArrayBuffer` *required*

The binary content of the file. Node `Buffer` is a `Uint8Array` subclass and is accepted.

**contentType** `string`

MIME type for the attachment. Defaults to `"application/octet-stream"` when the SDK wraps `Uint8Array` or `ArrayBuffer` in a `Blob`. Ignored when `content` is already a `Blob` or `File` (the Blob's own `type` is used instead).

## Supported content types

| Input type | Behavior |
| - | - |
| `Blob` / `File` | Passed as-is. `contentType` is ignored; the Blob's own `type` is used. |
| `Uint8Array` (includes Node `Buffer`) | Wrapped in a `Blob`. Uses `contentType` or `"application/octet-stream"`. |
| `ArrayBuffer` | Wrapped in a `Blob`. Uses `contentType` or `"application/octet-stream"`. |

## Size limits

The SDK enforces the following limits client-side. These match the BosonMail API limits:

| Limit | Value | Error message when exceeded |
| - | - | - |
| Maximum attachments per email | 10 | `A maximum of 10 attachments is allowed` |
| Maximum size per attachment | 10 MiB (10,485,760 bytes) | `Attachment "<filename>" exceeds the 10 MB per-attachment limit` |
| Maximum total attachment size | 20 MiB (20,971,520 bytes) | `Total attachment size exceeds the 20 MB limit` |

> [!NOTE]
>
> The SDK calculates sizes using binary mebibytes: `10 * 1024 * 1024` and `20 * 1024 * 1024` bytes.

## Transport: multipart/form-data

When `attachments` is present, the SDK sends a `multipart/form-data` request to `POST /emails/send`. The SDK does not set the `Content-Type` header; `fetch` generates the boundary automatically.

The form fields are:

| Field | Value |
| - | - |
| `to` | Recipient(s), arrays joined with `, ` after trimming |
| `subject` | Trimmed subject |
| `textContent` | Text body, if provided |
| `htmlContent` | HTML body, if provided |
| `cc` | CC recipients, arrays joined with `, ` |
| `bcc` | BCC recipients, arrays joined with `, ` |
| `attachments` | One field per attachment, with the filename |

> [!WARNING]
>
> The published README lists the endpoint as `POST /mail/send`, but the SDK source code (v0.2.0 and v0.2.1) calls `POST /emails/send`. The code is authoritative. Contact BosonWare at [support@bosonware.com](mailto:support@bosonware.com) to confirm the intended endpoint.

## Examples

### Read a file from disk (Node.js)

```typescript attach-file.ts theme={null}
import BosonMailClient from "@bosonware-ent/bosonmail";
import { readFile } from "node:fs/promises";

const client = new BosonMailClient({ apiKey: process.env.BOSONMAIL_API_KEY! });

const pdf = await readFile("./invoice.pdf");

const result = await client.sendEmail(
  "billing@example.com",
  "Invoice for October",
  {
    text: "Your invoice is attached.",
    attachments: [
      { filename: "invoice-october.pdf", content: pdf, contentType: "application/pdf" }
    ]
  }
);
```

### Read a file with Bun

Bun's `Bun.file()` returns a Blob-compatible object. Pass `arrayBuffer()` to be safe:

```typescript attach-file-bun.ts theme={null}
import BosonMailClient from "@bosonware-ent/bosonmail";

const client = new BosonMailClient({ apiKey: process.env.BOSONMAIL_API_KEY! });

const file = Bun.file("./report.pdf");
const content = await file.arrayBuffer();

const result = await client.sendEmail(
  "reports@example.com",
  "Monthly report",
  {
    text: "Please find the monthly report attached.",
    attachments: [
      { filename: "monthly-report.pdf", content, contentType: "application/pdf" }
    ]
  }
);
```

### Generate text content programmatically

```typescript attach-generated.ts theme={null}
import BosonMailClient from "@bosonware-ent/bosonmail";

const client = new BosonMailClient({ apiKey: process.env.BOSONMAIL_API_KEY! });

const csv = "name,amount\nAlice,100\nBob,200";
const encoder = new TextEncoder();
const content = encoder.encode(csv);

const result = await client.sendEmail(
  "data@example.com",
  "Export for today",
  {
    text: "The daily export is attached.",
    attachments: [
      { filename: "export.csv", content, contentType: "text/csv" }
    ]
  }
);
```

### Multiple attachments

```typescript attach-multiple.ts theme={null}
import BosonMailClient from "@bosonware-ent/bosonmail";
import { readFile } from "node:fs/promises";

const client = new BosonMailClient({ apiKey: process.env.BOSONMAIL_API_KEY! });

const pdf = await readFile("./invoice.pdf");
const csv = await readFile("./details.csv");

const result = await client.sendEmail(
  "billing@example.com",
  "Invoice and details",
  {
    text: "Your invoice and itemized details are attached.",
    attachments: [
      { filename: "invoice.pdf", content: pdf, contentType: "application/pdf" },
      { filename: "details.csv", content: csv, contentType: "text/csv" }
    ]
  }
);
```

## Pre-validating size in your application

You can check limits before calling the SDK to provide friendlier error messages:

```typescript validate-attachments.ts theme={null}
import type { SendAttachment } from "@bosonware-ent/bosonmail";

const MAX_ATTACHMENTS = 10;
const MAX_PER_FILE = 10 * 1024 * 1024;
const MAX_TOTAL = 20 * 1024 * 1024;

function validateAttachments(attachments: SendAttachment[]): string | null {
  if (attachments.length > MAX_ATTACHMENTS) {
    return `Too many attachments. Maximum is ${MAX_ATTACHMENTS}.`;
  }

  let total = 0;
  for (const att of attachments) {
    const size = att.content instanceof Blob
      ? att.content.size
      : att.content.byteLength;

    if (size > MAX_PER_FILE) {
      return `Attachment "${att.filename}" is too large. Maximum per file is 10 MB.`;
    }
    total += size;
  }

  if (total > MAX_TOTAL) {
    return `Total attachment size is too large. Maximum is 20 MB.`;
  }

  return null;
}
```

## Security considerations

* **Validate uploads in your application.** Check file types, sizes, and filenames before passing them to the SDK. Reject unexpected MIME types.
* **Sanitize filenames.** Strip path separators and control characters. Use a safe filename or generate one server-side.
* **Restrict MIME types.** Only allow attachment types your application expects (for example, PDF, CSV, images). Block executable files.
* **Scan for malware.** Run uploaded files through an antivirus or malware scanner before attaching them to outbound email.
* **Do not attach secrets.** Never attach API keys, credentials, or sensitive documents to automated emails.
* **Keep within limits.** Large attachments increase timeout risk and may be rejected by recipient servers. Consider hosting large files and linking instead.
* **Server-side only.** Call the SDK from your backend, never from browser code. The API key must not be exposed to clients.

> [!WARNING]
>
> Never accept arbitrary file paths from users. Always validate and sanitize file inputs. The SDK's client-side checks are a safety net, not a substitute for application-level validation.

> [card] [Sending emails](https://docs.bosonware.com/sdk/sending-emails.md)
>
> Full sendEmail reference with parameters and validation rules.

> [card] [CC and BCC](https://docs.bosonware.com/sdk/cc-and-bcc.md)
>
> How CC and BCC work with attachment requests.

> [card] [Guides: Attachments](https://docs.bosonware.com/guides/attachments.md)
>
> Step-by-step guide for handling file uploads and attaching them to emails.

> [card] [Error handling](https://docs.bosonware.com/sdk/error-handling.md)
>
> How to handle attachment validation and API errors.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.