Skip to content

Email Redaction

phileas-dotnet redacts email messages: .eml (MIME, message/rfc822) and Outlook .msg. Both are written out as .eml, a standard format any mail client opens; the proprietary .msg container is not rewritten. Messages are parsed and written with MimeKit, and .msg files are read with MsgReader and converted to MIME first. Both libraries are dependencies of the Phileas package, and the service runs on Linux, macOS, and Windows.

The policy's identifiers decide what is redacted in the message's text, as they do for plain text. The policy's config.email decides which headers are removed outright and what happens to attachments and inline images. Behavior follows the Java port (philterd/phileas#540) for the same policy and input, except for the features this library does not have yet (see Cross-port parity).

Quick start

using Phileas.Policy;
using Phileas.Services.Email;

var policy = PolicySerializer.DeserializeFromJson("""
{
  "identifiers": { "emailAddress": {}, "ssn": {} },
  "config": {
    "email": {
      "headers": { "removeTechnical": true, "removeIdentity": true, "removeDate": false, "removeSubject": false },
      "attachments": "redact",
      "inlineImages": "remove"
    }
  }
}
""");

var service = new EmailFilterService();
EmailFilterResult result = service.Filter(policy, "default", File.ReadAllBytes("message.msg"));

File.WriteAllBytes("message.redacted.eml", result.Document);

foreach (var part in result.Report.RemovedAttachments)
    Console.WriteLine($"Removed {part.FileName} ({part.ContentType}): {part.Reason}");

EmailFilterService takes an optional FilterService, as PdfFilterService does. Filter also takes an optional IContextService; one store of replacements is used for the whole message, so a value replaced in a header and the body is replaced the same way.

What is redacted

These fields are always redacted by the policy's identifiers:

  • the Subject, From, To, Cc, Thread-Topic (Outlook's copy of the subject), Keywords, and Comments headers, each by its decoded value, so an RFC 2047 encoded subject is redacted and written back encoded;
  • every text body part that is not an attachment: plain text, HTML, and the plain-text parts of delivery and disposition reports (message/delivery-status, message/disposition-notification, text/rfc822-headers, and their message/global-* forms);
  • the filename of each attachment that is removed or redacted, and of a forwarded message, since a filename can name a person.

HTML bodies are redacted as markup. Each HTML body is scanned twice: once as markup, which reaches attribute values such as a mailto: link, and once as its visible text, which reaches a value split by tags (john<span>@</span>example.com) or written with character references (john&#64;example.com). Spans found in the visible text are mapped back to the markup, and overlapping spans are merged. A value inside a cid: reference is left alone, since it names a part of the message. There is no setting for this.

Nested messages (message/rfc822 parts, such as a forwarded message) are processed the same way, recursively: their headers, body, and attachments follow the same settings.

A replacement can never end a header or start another: a carriage return or line feed in a header's replacement is written as a space.

config.email

Setting Values Default Effect
headers.removeTechnical boolean true Removes the technical headers (below).
headers.removeIdentity boolean true Removes the identity headers (below).
headers.removeDate boolean false Removes the Date header, whatever its format, without relying on a date identifier.
headers.removeSubject boolean false Removes the Subject and Thread-Topic headers instead of redacting them.
attachments keep, remove, redact remove What happens to attachments (below).
inlineImages keep, remove remove What happens to images embedded in the body and referenced by cid: (below).

A policy without config.email, or that leaves a setting out, gets these defaults. In PhiSQL the block is written CONFIGURE EMAIL ( ... ):

CONFIGURE EMAIL (
  headers = (removeTechnical = TRUE, removeIdentity = TRUE, removeDate = TRUE, removeSubject = FALSE),
  attachments = 'redact',
  inlineImages = 'remove'
);

The block is read strictly, whether or not the policy is validated against the schema: an unknown key, a header setting that is not true or false, and an attachments or inlineImages value outside its list are refused with a PolicyValidationException. Keys and values are case-sensitive. See Policies → Email.

Header groups

Header names match without regard to case. Removing a header removes the field entirely, not only its value, and a removed header is not scanned. Kept headers outside the redacted set are kept exactly as they are. Every setting applies to nested messages too.

Group Headers
Technical (removeTechnical) Received, Return-Path, Message-ID, User-Agent, X-Mailer, X-MimeOLE, DKIM-Signature, Authentication-Results, Received-SPF, Autocrypt, and every header beginning X- or ARC-
Identity (removeIdentity) Bcc, Reply-To, Sender, Delivered-To, Disposition-Notification-To, Return-Receipt-To, and every header beginning Resent-
Date (removeDate) Date
Subject (removeSubject) Subject, Thread-Topic

The redaction adds no header the input did not have: a message with no Date or Message-ID gets none.

Attachments

  • remove (the default) deletes each attachment, with its filename, and reports it with the reason Policy. A policy that says nothing about attachments therefore never returns content nobody inspected.
  • keep returns attachments as they are, uninspected and unredacted, and reports each one by its own filename as uninspected.
  • redact redacts each supported attachment with the same policy and keeps it, with its redacted filename:
Attachment Recognized by Redacted with
PDF application/pdf, a .pdf filename, or an unnamed application/octet-stream part that starts with %PDF- PdfFilterService (the attachment is rasterized, as any redacted PDF is)
Word its media type, a .docx filename, or an unnamed application/octet-stream Word package WordDocumentRedactor
Excel its media type, an .xlsx filename, or an unnamed application/octet-stream Excel package XlsxRedactor
Plain text text/plain on a part with an attachment disposition or a filename, or a .txt file sent as application/octet-stream the policy's identifiers, as text

A text/plain part with no attachment disposition and no filename is body text, not an attachment.

A plain-text attachment is read and written in the character set its part declares, otherwise UTF-8, strictly: text that is not valid in that character set, or a redaction the character set cannot hold, is refused rather than misread or written as ?. It keeps its filename and media type, and a part that declared no charset is labeled with the one it was written in, so the label matches the bytes. A part that is not text gets no charset.

RTF attachments (application/rtf, text/rtf, a .rtf filename, or an unnamed application/octet-stream part that starts with {\rtf) and CSV attachments (text/csv or a .csv filename) are recognized, but this library does not redact those formats yet (#222, #230), so under redact they are removed and reported as UnsupportedType. Any other attachment, such as an image, an archive, or a legacy .doc, is removed and reported as UnsupportedType. A supported attachment its redaction refuses, such as a damaged file, text not valid in its character set, or a character set .NET does not know, is removed and reported as RedactionFailed. Under redact, an attachment is never kept unredacted.

A forwarded message attached as a file is removed under remove, and redacted as a nested message under keep and redact.

Inline images

remove (the default) deletes each image embedded in the body (an image/* part marked inline or with a Content-ID) and points every cid: reference to it at about:blank, so no reference dangles. keep leaves them, uninspected, and reports them. The setting is independent of attachments.

Signed and encrypted messages

A signed message (multipart/signed, S/MIME or PGP) is redacted, and its signature part is dropped, since redacting invalidates it; the drop is reported. An encrypted message (application/pkcs7-mime, multipart/encrypted, application/pgp-encrypted, a PGP-armored body, or an encrypted Outlook message), or a message with one nested in it, is refused with an EncryptedEmailException. It is never passed through unredacted.

Outlook .msg

The subject, sender, recipients (To, Cc, and Bcc), date, bodies, and attachments are carried over, and an embedded message becomes a nested message/rfc822 part. The identity setting then decides whether the Bcc recipients are kept. The transport headers an Outlook message may hold are not carried over.

A message whose only body is RTF has that body read as plain text, so it is not dropped. The RTF is read by the library itself, with no Windows API: paragraphs become lines and table cells are separated by tabs, and font tables, pictures, objects, headers and footers, field instructions, hidden text, and tracked deletions are left out, as are the RTF-only and HTML-only parts of HTML encapsulated in RTF. An RTF body that is malformed (unclosed groups, a bad escape, or nesting deeper than 1,000 groups) is refused with a FormatException. The library registers .NET's Windows code pages, which MsgReader and many messages need.

EmailFilterService.IsOutlookMessage(bytes) tells whether input is a .msg.

The result

EmailFilterResult has:

Property Description
Document The redacted message, as .eml.
Spans The spans applied to the message's fields, as OfficeRedactionSpan. Each span's ParagraphIndex is its field's number and its offsets are into that field's text. Spans inside redacted attachments are not listed.
Fields The message's fields (EmailField), with each one's Index, MessageNumber, Label, IsHtml, IsBody, Text, and Output.
Report What was left uninspected or taken out (below).
Tokens The whitespace-delimited tokens in the fields and the redacted attachments.
ReviewSampled Whether the policy's review sampling selected the message. The draw is made once per message.

Report (EmailReport) lists, each as an EmailReportPart with its FileName, ContentType, MessageNumber (0 for the message itself, otherwise the nested message's number, from 1 in document order), and Reason:

List Contents
UninspectedAttachments Attachments kept under attachments: keep, by their own filenames. Their content was not inspected.
UninspectedInlineImages Inline images kept under inlineImages: keep.
RemovedAttachments Attachments removed, with the reason Policy, UnsupportedType, or RedactionFailed, by their redacted filenames.
RemovedInlineImages Inline images removed under inlineImages: remove.
DroppedSignatures Signature parts dropped from signed messages.

HasNotices is true when any list is not empty. A caller, or a leftover check, can use the report to warn that kept attachments or images were not inspected.

Detect, review, and apply

A review preview, such as Philter Desktop's, redacts in three steps instead of one:

var service = new EmailFilterService();

// 1. The fields a redaction with this policy would redact, with their text.
IReadOnlyList<EmailField> fields = service.ReadFields(policy, input);

// 2. The spans, by field, without redacting attachments or writing anything.
List<OfficeRedactionSpan> spans = service.Detect(policy, "default", input);

// 3. The message with the spans the reviewer kept, plus any they added.
byte[] eml = service.Apply(policy, input, keptSpans);

Fields are numbered in a fixed order: each message's Subject, From, To, Cc, Thread-Topic, Keywords, and Comments headers (one field per occurrence), then its body parts and the filenames of its removed or redacted attachments in document order, with a nested message's fields where the message is. The numbering depends on the policy, since a removed header is not a field and the filename of an attachment kept uninspected is not one, so pass the same policy to all three calls.

Apply applies each span by position. A span with no replacement is replaced with {{{REDACTED-custom}}}, a span outside its field is ignored, and overlapping spans are merged, keeping the first one's replacement. Headers, attachments, and inline images are handled by config.email, as in Filter, and attachments are redacted with the policy. Applying every span Detect returns gives the same message as Filter.

Cross-port parity

Container format .NET Java Python
Email .eml and .msg ✅ ✅ ❌

The Java port also redacts RTF and CSV attachments, offers text output for email, and runs the policy's leftover check over the message and its redacted attachments. This library does not have those yet: RTF and CSV redaction are #222 and #230, and the leftover check is #219.