# Email messages (.msg and .eml)

> Parse Outlook .msg and RFC 5322 .eml files, convert them to a paginated PDF with the header block, the HTML or plain body, inline images and the original attachments, and open them directly in the viewer.

Birch UI PDF reads Outlook `.msg` files and `.eml` files and turns them into PDF. The parsers and the converter are DOM-free, run in the browser and in Node, and never make a network request: remote images are not fetched and links are written as link annotations, never followed.

## Parsing a message

```ts
import { parseEml, parseMsg } from '@birchui/pdf/engine';

const fromOutlook = parseMsg(msgBytes);
const fromMime = parseEml(emlBytes);

console.log(fromOutlook.subject, fromOutlook.from?.address, fromOutlook.sentAt?.toISOString());
for (const attachment of fromMime.attachments) {
  console.log(attachment.fileName, attachment.mimeType, attachment.data.length, attachment.isInline);
}
```

Both functions return the same `MailMessage`:

| Field | Meaning |
| --- | --- |
| `format` | `'msg'` or `'eml'` |
| `subject` | Decoded subject, `''` when there is none |
| `from` | `{ name, address }`, absent when the message names no sender |
| `to`, `cc`, `bcc` | Lists of `{ name, address }` |
| `sentAt` | Sent date as a `Date`, absent when the message has none |
| `text` | Plain text body, `''` when there is none |
| `html` | HTML body, `''` when there is none |
| `headers` | Transport headers in file order as `{ name, value }`, unfolded and decoded |
| `attachments` | `{ fileName, mimeType, data, contentId?, isInline, embeddedMessage? }` |

An attached message is parsed recursively into `embeddedMessage`. For `.eml` the attachment's `data` holds the original bytes of the attached message; an Outlook message embedded in a `.msg` is stored as a sub-storage and has no bytes of its own, so its `data` is empty.

`parseMail(bytes, { fileName, mimeType })` picks the parser for you, and `detectMailFormat(bytes, hint)` returns `'msg'`, `'eml'` or `undefined` without parsing. A compound file is recognised by its signature, an `.eml` by its file name, the `message/rfc822` type or its leading header lines.

Malformed input throws a `MailFormatError`. Sector chains, the directory tree, MIME nesting and attached-message depth are all bounded, so a damaged or hostile file fails instead of hanging.

```ts
import { MailFormatError, parseMail } from '@birchui/pdf/engine';

declare const uploadBytes: Uint8Array;

try {
  const message = parseMail(uploadBytes, { fileName: 'inquiry.msg' });
  console.log(message.to.map((recipient) => recipient.address));
} catch (error) {
  if (error instanceof MailFormatError) console.warn('Not a readable message:', error.message);
  else throw error;
}
```

### What the .msg reader covers

- Compound files with 512 and 4096 byte sectors, the mini stream and DIFAT sectors.
- Unicode and ANSI string properties; ANSI strings are decoded with the message code page.
- Sender, represented sender, recipients by type (To, Cc, Bcc) with the SMTP address preferred over an Exchange address, submit and delivery time, transport headers.
- The plain body, the HTML body in its internet code page, and compressed RTF in both the LZFu and the uncompressed form. HTML that Outlook wrapped in RTF is recovered; other RTF is converted to plain text.
- Attachments with their long file name, MIME type and content id, and embedded messages.

`decompressRtf(bytes, { verifyCrc })`, `rtfToHtml(rtf)` and `rtfToText(rtf)` are exported for callers that hold the compressed RTF property themselves. The checksum is only enforced when `verifyCrc` is `true`.

### What the .eml reader covers

- Header unfolding, encoded words in `B` and `Q` form, including adjacent words that split one character.
- Parameter continuations and charsets for file names (`filename*0*=`), quoted and encoded names.
- `multipart/mixed`, `alternative` and `related` at any depth, `quoted-printable`, `base64`, `7bit` and `8bit` bodies.
- Charsets through `TextDecoder`; an unknown label falls back to Windows-1252.
- Address lists with quoted display names, comments and groups.
- Inline parts by `Content-ID` and `message/rfc822` parts as embedded messages.

## Converting to PDF

```ts
import { mailToPdf, parseMsg } from '@birchui/pdf/engine';

const message = parseMsg(msgBytes);
const result = await mailToPdf(message, {
  pageSize: 'a4',
  margin: 48,
  fontSize: 10,
  attachOriginal: { data: msgBytes, fileName: 'signed-contract.msg' },
});

console.log(result.pageCount, result.attachmentNames, result.warnings);
```

The first page starts with a header block: the subject, then From, To, Cc, Bcc, Sent and the attachment names with their sizes. The body follows and flows over as many pages as it needs. The document title is the subject, the author is the sender and the creation date is the sent date.

| Option | Default | Meaning |
| --- | --- | --- |
| `pageSize` | `'a4'` | `'a4'`, `'letter'` or `{ width, height }` in points |
| `margin` | `48` | Points on every side, or `{ top, bottom, left, right }` |
| `fontSize` | `10` | Body size in points, between 6 and 36 |
| `fonts` | | A font registry or a list of `{ name, data }` TrueType or OpenType fonts for text outside Windows Latin |
| `includeAttachments` | `true` | Embed the attachments as document-level file attachments |
| `attachOriginal` | | The source bytes, or `{ data, fileName }`, embedded as well |
| `preferPlainText` | `false` | Use the plain body even when the message has an HTML body |
| `labels` | English | Replace `subject`, `from`, `to`, `cc`, `bcc`, `sent`, `attachments`, `noSubject`, `image` |
| `formatDate` | UTC, `YYYY-MM-DD HH:mm UTC` | Format the sent date yourself |

The result is `{ bytes, pageCount, substitutedCharacters, attachmentNames, warnings }`. Each warning has a `code`, a `message` and a `count`:

| Code | When |
| --- | --- |
| `substituted-characters` | Characters that no available font covers were written as `?` |
| `remote-image` | An image with an `http` or other remote address was replaced by a placeholder box with its alternative text |
| `missing-image` | A `cid:` image that the message does not contain |
| `unsupported-image` | An inline image that is not PNG or JPEG |
| `unsafe-link` | A link without a scheme or with an unsafe one, written as plain text |
| `embedded-message-converted` | An Outlook message embedded in a `.msg`, attached as a converted PDF |

### The HTML body

The HTML body is preferred. It is read with a small built-in parser, not a browser engine:

- Paragraphs, line breaks, headings, bold, italic and monospace text, preformatted blocks and horizontal rules.
- Links as link annotations with a URI action, for `http`, `https`, `mailto` and the other schemes `isSafeLinkUri` accepts.
- Ordered and unordered lists, nested, and block quotes with an indent and a bar.
- Tables as a grid of equal-width columns with wrapped text. A table with one cell per row is treated as layout and its content flows as ordinary blocks.
- Images referenced by `cid:` from the message's inline attachments, and `data:` images, when they are PNG or JPEG.
- `head`, `style`, `script` and comments are dropped; named and numeric entities are decoded.

A message without an HTML body, or with one that yields no content, is rendered from its plain text.

### Attachments

Every attachment is embedded with its original bytes, file name and MIME type, so `pdfdetach` or any PDF reader returns the files unchanged. An inline image that the page already shows is not embedded a second time; an inline part the body does not show is embedded. Two attachments with the same name get a numbered suffix. An attached `.eml` is embedded as its original bytes. An Outlook message embedded in a `.msg` is converted with the same options and attached as a PDF.

### Text outside Windows Latin

Without `fonts`, text is drawn with the standard Helvetica and Courier fonts. A character they cannot show is written as `?` and counted in `substitutedCharacters`. Pass fonts to keep the text:

```ts
import { mailToPdf, parseEml } from '@birchui/pdf/engine';

declare const notoSans: Uint8Array;

const result = await mailToPdf(parseEml(emlBytes), { fonts: [{ name: 'Noto Sans', data: notoSans }] });
console.log(result.substitutedCharacters);
```

## In the viewer

`viewer.load`, `viewer.openTab`, the `document` option and a file dropped on the viewer accept `.msg` and `.eml` files. The viewer detects them, converts them and shows the PDF. The mail code is loaded on demand the first time a mail file is opened, so it adds nothing to the initial bundle.

```ts
import { createPdfViewer } from '@birchui/pdf';

const viewer = createPdfViewer(container, {
  allowFileDrop: true,
  convertMail: { attachOriginal: true, pageSize: 'letter' },
});

viewer.on('mailConversion', ({ format, sourceFileName, fileName, pageCount, message, warnings }) => {
  console.log(`${sourceFileName} (${format}) opened as ${fileName} with ${pageCount} pages`);
  console.log(message.subject, message.from?.address, message.attachments.length, warnings);
});

await viewer.load(msgBytes, { fileName: 'signed-contract.msg' });
```

- `convertMail` is `true` by default. `false` turns the conversion off; an object passes `mailToPdf` options, where `attachOriginal: true` embeds the opened file. The viewer's `fonts` option is used unless `convertMail.fonts` is set.
- `mailConversion` fires before `documentLoad`. Its `message` carries `subject`, `from`, `to`, `cc`, `sentAt` and the attachment list with `fileName`, `mimeType`, `size` and `isInline`.
- The file name of the opened document becomes the source name with a `.pdf` extension, which `download` and the `save` event then use.
- A file that looks like mail but cannot be parsed fails the load like a damaged PDF: `load` rejects and `documentError` fires with the `MailFormatError`.

## Limits

- No S/MIME or PGP: encrypted messages are not decrypted and signatures are not verified. A signed or encrypted part appears as an ordinary attachment.
- No TNEF: a `winmail.dat` attachment is embedded as it is and not unpacked.
- Outlook items other than mail (appointments, contacts, tasks) are read as far as they share the mail properties; their own fields are not shown.
- Named properties, voting buttons, categories, flags and read receipts are not read.
- RTF bodies that are not HTML wrapped in RTF are rendered as plain text; RTF formatting, tables and embedded OLE objects are dropped.
- CSS is ignored: no colours, fonts, sizes, alignment, floats or background images. Column widths and cell spans beyond `colspan` are not honoured, and nested tables inside a grid cell are flattened to text.
- Text inside grid table cells loses its inline formatting and links.
- GIF, WebP, SVG and BMP images are not drawn. Remote images are never fetched.
- Right-to-left lines are drawn in one run in visual order and lose inline formatting. Complex shaping beyond what the font registry does is not applied.
- Each line of text drawn with a supplied font embeds its own small font subset, so long messages in non-Latin scripts produce larger files.
- Multi-byte charsets depend on the `TextDecoder` of the runtime.
- An Outlook message embedded in a `.msg` cannot be re-attached as a `.msg` file; it is attached as a PDF.
- The whole message is held in memory; there is no streaming parser.
