mail_deduplicate.mail module¶

A mail wrapped with the properties deduplication needs.

They are the canonical hash, the normalized headers, the timestamp, the size, and the dehydration that keeps memory flat.

exception mail_deduplicate.mail.TooFewHeaders[source]¶

Bases: Exception

Not enough headers were found to produce a solid hash.

class mail_deduplicate.mail.TimeSource(*values)[source]¶

Bases: StrEnum

Enumeration of all supported mail timestamp sources.

DATE_HEADER = 'date-header'¶

Timestamp sourced from the message’s Date header.

CTIME = 'ctime'¶

Timestamp is from the email’s file on the filesystem.

Attention

Only meaningful for sources storing one mail per file, like maildir, mh and eml.

MTIME = 'mtime'¶

Timestamp is the modification time of the email’s file on the filesystem.

For a maildir mail, it is the time the mail arrived. A client sets a flag by renaming the file, which keeps this time but changes the ctime.

Attention

Only meaningful for sources storing one mail per file, like maildir, mh and eml.

mail_deduplicate.mail.ADDRESS_HEADERS = frozenset({'bcc', 'cc', 'delivered-to', 'disposition-notification-to', 'envelope-to', 'from', 'original-recipient', 'reply-to', 'resent-bcc', 'resent-cc', 'resent-from', 'resent-reply-to', 'resent-sender', 'resent-to', 'return-path', 'sender', 'to', 'x-envelope-from', 'x-envelope-to', 'x-original-to'})¶

Headers that contain email addresses.

Hint

Headers from which quotes should be discarded, so "Bob" <bob@example.com> hashes to the same thing as Bob <bob@example.com>.

Attention

These IDs should be kept lower-case, because they are compared to the IDs provided to the -h/--hash-header option, carried by the hash_headers entry of the configuration.

mail_deduplicate.mail.HEADER_LINE = re.compile(b'\\A(From |[!-9;-~]*:|[\\t ])')¶

A line of the header block, as the parser reads one: an envelope line, a header or a folded continuation.

The parser ends the headers on the first blank line, or on the first line that is none of these when the blank line is missing. split_raw() follows the same rule.

mail_deduplicate.mail.LINE = re.compile(b'[^\\r\\n]*[\\r\\n]|[^\\r\\n]+\\Z')¶

One line of a mail with LF line endings, with its line break when it has one.

A bare CR also ends a line, as it does for the parser.

class mail_deduplicate.mail.DedupMailMixin(message=None)[source]¶

Bases: Message

Message with deduplication-specific properties and utilities.

Extends standard library’s mailbox.Message, and shouldn’t be used directly, but composed with mailbox.Message sub-classes.

Initialize a Message instance.

CONTENT_CACHES: tuple[str, ...] = ('body_lines', 'canonical_headers', 'hash_decoded_body', 'hash_normalized_body', 'hash_raw_body')¶

Memoized properties derived from the message content.

They are only needed while computing hashes, and are dropped by dehydrate() alongside the parsed message itself.

resolve_path: Callable[[Mailbox, str], str]¶

Derives the real filesystem location of a mail from its box.

Set per box format by make_dedup_mail(), as folder-based boxes give each mail its own file while file-based ones pack them all into the box’s single file.

defects: list = ()¶

Fallback for the parsing defects dropped by dehydrate().

An empty tuple rather than a list, so it can be shared by every dehydrated mail instead of costing one throw-away empty list each: reads still work, and the appends only the parser performs fail loudly on a mail that has no message.

PARSED_MESSAGE_ATTRS: tuple[str, ...] = ('_headers', '_payload', '_unixfrom', 'preamble', 'epilogue', 'defects')¶

Attributes carrying the parsed message, as populated by email.parser.

They hold the bulk of a mail’s memory footprint, and are the ones dropped by dehydrate() and restored by hydrate().

box: Mailbox | None¶

The box this message was read from, kept to re-fetch its content on demand after dehydration.

source_path: str | None¶

Normalized path to the mailbox this message originates from.

mail_id: str | None¶

Mail ID used to uniquely refers to it in the context of its source.

conf: Config¶

Global configuration

property path: str¶

Real filesystem location of the mail.

Returns the individual mail’s file for folder-based box types (maildir & co.), but returns the whole box path for file-based boxes (mbox & co.). Used by regexp-based selection strategies and to render the mail’s repr.

Derived on access from the box rather than stored, so a retained mail does not carry a copy of its own absolute path for the whole run. Raises AttributeError before the box metadata is attached, so getattr(mail, “path”, None) still reads as absent.

add_box_metadata(box, mail_id)[source]¶

Attach to the mail some metadata derived from its parent box.

Called right after the __init__() constructor.

This allows the mail to carry its own information on its origin box and index.

Return type:

None

property is_hydrated: bool¶

Whether the mail still carries its parsed message.

dehydrate()[source]¶

Reduce the mail to the lightweight metadata needed by the next steps.

Memoizes the scalar properties consumed by selection strategies (timestamp, and size when the decoded body is at hand), then drops the parsed message and every cached copy of its content. This cuts the resident footprint of a retained mail from the full size of its message to a few hundred bytes, whatever the number of mails processed. See: https://github.com/kdeldycke/mail-deduplicate/issues/761

No-op if the mail is already dehydrated. The dropped content is re-read from the source box by hydrate() when a later step needs it again.

Return type:

None

hydrate()[source]¶

Restore the full parsed message dropped by dehydrate().

Re-reads the mail from its source box, through the same parsing path that produced it in the first place, so the restored content is identical. No-op if the mail still carries its parsed message.

Return type:

None

raw_bytes()[source]¶

Read the bytes of the mail again, from its own file or from its box.

The parser consumed them without keeping them. A mail a worker opened by path is read from that file. A mail of the main process is read from its box, which hands it out without the envelope line and the state its format keeps beside each mail.

Return type:

bytes

hydrated()[source]¶

Borrow the full parsed message for the duration of the block.

Restores the message on the way in and releases it on the way out, so a step needing the whole mail after the hashing one keeps its content resident only while it uses it, and memory stays flat across a loop of mails.

Return type:

Generator[DedupMailMixin, None, None]

property parsed_date: float | None[source]¶

Parse the mail’s date header into float timestamp.

Returns None if the mail has no valid date header, or one whose year no timestamp can hold.

Self-hydrating: re-reads the message from its box if it was dehydrated.

property timestamp: float | None[source]¶

Compute the normalized canonical timestamp of the mail.

Sourced from the message’s Date header by default, or from a time of the email’s file on the filesystem: see TimeSource.

Warning

ctime does not refer to creation time on POSIX systems, but rather the time of the last metadata change.

Note

MaildirMessage.get_date() cannot serve the mtime source. Maildir.get_message() sets that date from the modification time of the mail file. But a box with a message factory, as every box of mdedup has, reads a mail with that factory and skips get_message(). The date of such a mail is the time it was read, so the mtime source reads the file instead.

property size: int[source]¶

Returns the canonical size of the mail, in bytes.

The size is the byte length, in UTF-8, of the decoded body: the payload of the mail stripped of its headers, its transfer encodings undone and its text decoded, never the size of the mail on disk. Copies of a mail that differ in their transfer encoding alone measure the same, and --size-threshold compares them in the unit it names.

property body_lines: list[str][source]¶

Return the lines of the decoded body of the message.

Each text part has its transfer encoding undone and its text decoded with its charset, so copies of a mail that differ in their encoding alone read the same. A part that is not text is kept as the mail carries it. The preamble and epilogue of a multipart are read as UTF-8.

Self-hydrating: re-reads the message from its box if it was dehydrated.

decode_part(part)[source]¶

Decode a single message part to string.

Return type:

str

undo_surrogateescape(text, errors='replace')[source]¶

Decode as UTF-8 the non-ASCII bytes that parsing left as lone surrogates.

A mail parsed from bytes keeps each non-ASCII byte as a lone surrogate, and encoding such a string to UTF-8 raises UnicodeEncodeError. get_payload() undoes this for each part, with the charset of the part. The preamble and the epilogue have no charset, so they go through here instead. Bytes that are not valid UTF-8 become U+FFFD, as get_payload() does with its charset, unless errors names another way out, like backslashreplace.

Encoding with utf-8 instead of ascii keeps the non-ASCII characters of a mail parsed from a string, which ascii rejects.

Return type:

str

hash_key()[source]¶

Returns the canonical hash of a mail.

Under --raw-headers, the hash is that of the header block, as raw_headers() reads it: every header takes part, so no minimal number of them applies.

Caution

This method hasn’t been made explicitly into a cached property in order to reduce the overall memory footprint.

Return type:

str

split_raw()[source]¶

The bytes of the mail as the box holds them, cut into headers and body.

Line endings are reduced to LF, as add_mail() writes them: every box format rewrites them to the separator of the platform, and the mbox reader reduces them on Windows, so a mail would otherwise never hash like its own export, and a hash would depend on the platform. Nothing else is interpreted. A header a server or a client added, an mbox >From quote and a transfer encoding all count.

The header block ends with the first blank line, which it keeps. When that blank line is missing, it ends before the first line that is neither a header nor a continuation, where the parser starts the body too. A mail of headers alone has an empty body. The two halves always join back into the whole mail, so --raw-headers with --hash-body raw hashes every byte.

Return type:

tuple[bytes, bytes]

raw_headers()[source]¶

The header block of the mail, as split_raw() cuts it.

Return type:

bytes

raw_body()[source]¶

The body bytes of the mail, as split_raw() cuts them.

Return type:

bytes

property hash_raw_body: str[source]¶

Returns the hash of the body bytes, as the box holds them.

Nothing but the line endings is interpreted, see raw_body(): a transfer encoding, a charset, a bare CR and an mbox >From quote all count, where hash_decoded_body reads through the first two.

property hash_decoded_body: str[source]¶

Returns the hash of the decoded body of a mail, line by line.

property hash_normalized_body: str[source]¶

Returns the hash of the decoded body of a mail, stripped of whitespace.

property canonical_headers: tuple[tuple[str, str], ...][source]¶

Returns the canonical header names and values, ready for hashing.

Under --raw-headers, it returns every header instead, in its order and unnormalized, for --hash-only to show. The hash itself reads the bytes of the header block: see raw_headers().

Self-hydrating: re-reads the message from its box if it was dehydrated.

pretty_canonical_headers()[source]¶

Renders a table of headers names and values used to produce the mail’s hash.

Caution

This method hasn’t been explicitly made into a cached property in order to reduce the overall memory footprint.

Returns a string ready to be printed.

Return type:

str

serialized_headers()[source]¶

Serialize the canonical headers into a single string ready to be hashed.

At this point we should have an absolute minimum of headers.

Caution

This method hasn’t been explicitly made into a cached property in order to reduce the overall memory footprint.

Return type:

bytes

header_text(value)[source]¶

The text of one header value, as the mail holds it.

A header holding raw 8-bit bytes is read as those bytes: decoded as UTF-8 where they are valid UTF-8, and escaped byte by byte elsewhere. get() and get_all() hand such a header over as a Header, which string functions like email.utils.parsedate_tz() reject. Its text also replaces every such byte with U+FFFD, under which two headers differing in those bytes alone read, and hash, alike.

Return type:

str

header_values(header_id)[source]¶

Returns the text of each occurrence of a header, in the order of the mail.

Each value reads as header_text() reads it.

Return type:

Iterator[str]

normalized_header_values(header_id)[source]¶

Returns all normalized values of a header.

Values are cleaned-up into their canonical form, from the text header_values() reads.

Return type:

Iterator[str]

normalize_subject(subject)[source]¶

Strip Re:/Fwd: and [list-name] prefixes from Subject.

This cleans up prefixes automatically added by mailing list software, since the mail could have been CC’d to multiple lists, in which case it will receive a different prefix for each.

Return type:

str

normalize_content_type(value)[source]¶

Normalize Content-Type by stripping parameters.

Removes everything after the semicolon, keeping only the MIME type. E.g., text/plain; charset=utf-8 becomes text/plain.

Apparently list servers actually munge Content-Type e.g. by stripping the quotes from charset="us-ascii". Section 5.1 of RFC2045 says that either form is valid (and they are equivalent).

Additionally, with multipart/mixed, boundary delimiters can vary by recipient. We need to allow for duplicates coming from multiple recipients, since for example you could be signed up to the same list twice with different addresses. Or maybe someone bounces you a load of mail some of which is from a mailing list you’re both subscribed to - then it’s still useful to be able to eliminate duplicates.

Return type:

str

normalize_date(value)[source]¶

Normalize Date to YYYY-MM-DD format.

Date timestamps can differ by seconds or hours for various reasons, so only the date is honoured, normalized to the UTC timezone.

Todo

Revisit the day-level granularity, and whether the time of the day should take part in the hash.

Return type:

str

normalize_address_header(value)[source]¶

Normalize address headers by removing quotes and collapsing whitespace.

E.g., "Bob" <bob@example.com> becomes Bob <bob@example.com>.

Remove quotes in any headers that contain addresses to ensure a quoted name is hashed to the same value as an unquoted one.

Danger

This may not be the cleanest way to normalize email addresses. E.g. "Robert \"Bob\"" becomes Robert \Bob\, but this shouldn’t matter for hashing purposes as we’re just trying to get a good heuristic. Refs: #846 and #847.

Return type:

str

normalize_message_id(value)[source]¶

Normalize Message-ID header by stripping angle brackets.

E.g., <unique-id@example.com> becomes unique-id@example.com.

Return type:

str

strip_angle_brackets(value)[source]¶

Strip angle brackets from a value if it’s a single bracketed item.

Only strips if the value matches <something> with no commas.

Note

Sometimes email.parser strips the <> brackets from a To: header which has a single address. I have seen this happen for only one mail in a duplicate pair. I’m not sure why (presumably the parser uses email.utils.unquote somewhere in its code path which was only triggered by that mail and not its sister mail), but to be safe, we should always strip the <> brackets to avoid this difference preventing duplicate detection.

Return type:

str