---
title: "Rewrite a MIME header in C# without changing the other parts"
url: https://recursiveai.org/onemail/cookbook/preserve-mime-source-when-rewriting-mail/
description: "Change the Subject of a MIME email in C# and copy untouched headers, boundaries, and attachment bytes as written. Includes a runnable OneMail example."
version: "1.0.1"
---

# Rewrite a MIME header in C# without changing the other parts

**OneMail** is a free, open-source email library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneMail) · [GitHub](https://github.com/recursive-ai-oss/onemail-csharp) · [Docs](https://recursiveai.org/onemail/docs/) · [Download example (.zip)](https://recursiveai.org/onemail/cookbook/preserve-mime-source-when-rewriting-mail/preserve-mime-source-when-rewriting-mail.zip)

Change the subject of `sample.eml` from the zip without changing any other bytes.

```shell
dotnet add package RecursiveAI.OneMail
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneMail.Mime.Reading;
using RecursiveAI.OneMail.Mime.Writing;
using var input = File.OpenRead("sample.eml");
using var reader = new MimeReader(input);
using var output = File.Create("rewritten.eml");
using var writer = new MimeWriter(output);
while (reader.Read())
    if (reader.Depth == 0 &&
        reader.Kind == MimeEventKind.Header &&
        // Exact case here; the full program ignores case.
        reader.HeaderName
              .SequenceEqual("Subject"u8))
        writer.WriteHeader(
            "Subject", "Route confirmed");
    else
        writer.WriteEvent(reader);
```

Unzip [the example](https://recursiveai.org/onemail/cookbook/preserve-mime-source-when-rewriting-mail/preserve-mime-source-when-rewriting-mail.zip), then `dotnet run`.

Writes `rewritten.eml` with `Subject: Route confirmed` in place of `Subject: Route draft`.

## The full program

The bundled message has a plain-text part and a base64 attachment. Here’s an excerpt from the input; `--trail` separates the parts:

```text
Subject: Route draft
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="trail"

--trail
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

Meet=20at=20nine.
```

The downloaded program matches the first top-level `Subject` regardless of case. It stages the result in memory and throws `InvalidDataException` before writing the output file if the reader hit its total-size limit or no subject was found.

```csharp
using RecursiveAI.OneMail.Mime.Reading;
using RecursiveAI.OneMail.Mime.Writing;
using System.Text;

using var input = File.OpenRead("sample.eml");
using var reader = new MimeReader(input);
using var output = new MemoryStream();
using var writer = new MimeWriter(output);

bool replaced = false;
while (reader.Read())
{
    if (!replaced && reader.Depth == 0 &&
        reader.Kind == MimeEventKind.Header &&
        Ascii.EqualsIgnoreCase(reader.HeaderName, "Subject"u8))
    {
        writer.WriteHeader("Subject", "Route confirmed");
        replaced = true;
    }
    else
    {
        writer.WriteEvent(reader);
    }
}

if (reader.IsTruncated || !replaced)
    throw new InvalidDataException("Input truncated or no Subject header.");

writer.Flush();
File.WriteAllBytes("rewritten.eml", output.ToArray());
Console.WriteLine("Wrote rewritten.eml");
```

`dotnet run` prints:

```text
Wrote rewritten.eml
```

## Variations

**Copy the message without editing it.** In the snippet at the top, replace the loop with this to write the sample as it was received:

```csharp
while (reader.Read())
    writer.WriteEvent(reader);
```

## Related recipes

- [Parse an email message](https://recursiveai.org/onemail/cookbook/parse-eml/)
- [Extract attachments from an email](https://recursiveai.org/onemail/cookbook/extract-attachments/)

## The short answer

Use `MimeReader` to read the message and `MimeWriter.WriteEvent(reader)` to copy each event as raw bytes. When the reader reaches the header you want to change, write a new header instead of copying that event. A MIME event here is a piece of the original source, such as one header field, a boundary line, or a chunk of body. That distinction lets you change the subject without decoding and encoding the attachment again.

## How do I change the subject line of a MIME email in C#?

Match a `Header` event for `Subject` at `Depth == 0`. Depth zero is the outer message; leaving it out can match headers inside a forwarded message too. A folded subject field, with its continuation lines, is still one event. `WriteHeader` replaces the whole field, including the old folding. The short snippet matches the spelling in the sample. The full program matches case-insensitively and replaces only the first matching field, so it won’t rewrite several duplicate subjects in an imperfect message. It doesn’t add a subject if none was present.

Use this pattern for a descriptive header such as `Subject`. Don’t change a structural field such as `Content-Type` to a new multipart boundary while copying the old body unchanged: the field and its delimiter lines need to agree. The [MIME reading guide](https://recursiveai.org/onemail/docs/mime-reading/) lists the exact bytes covered by each event.

## How do I keep the multipart body unchanged when I edit a header?

Pass through the other headers, their separating blank lines, the MIME delimiters, and each body chunk with `WriteEvent`. The writer copies the original bytes; it doesn’t fold an untouched header again or alter base64 wrapping. In the sample, the literal `Meet=20at=20nine.` and the `--trail` lines stay in the output. The new subject is written with the writer’s formatting rules, not the old subject’s spacing or folding.

The example saves to a second file so the source stays available. For larger messages, you can write to a separate staging file instead of keeping the whole output in memory. In either case, check `reader.IsTruncated` after reading and before keeping the result. The reader’s total-byte limit can stop it before the end of the input, so copying every event you received is not enough to declare that the input was copied in full.
