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:
ExceptionNot enough headers were found to produce a solid hash.
- class mail_deduplicate.mail.TimeSource(*values)[source]¶
Bases:
StrEnumEnumeration of all supported mail timestamp sources.
- DATE_HEADER = 'date-header'¶
Timestamp sourced from the message’s
Dateheader.
- CTIME = 'ctime'¶
Timestamp is from the email’s file on the filesystem.
Attention
Only meaningful for sources storing one mail per file, like
maildir,mhandeml.
- MTIME = 'mtime'¶
Timestamp is the modification time of the email’s file on the filesystem.
For a
maildirmail, it is the time the mail arrived. A client sets a flag by renaming the file, which keeps this time but changes thectime.Attention
Only meaningful for sources storing one mail per file, like
maildir,mhandeml.
- 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 asBob <bob@example.com>.Attention
These IDs should be kept lower-case, because they are compared to the IDs provided to the
-h/--hash-headeroption, carried by thehash_headersentry 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:
MessageMessage with deduplication-specific properties and utilities.
Extends standard library’s mailbox.Message, and shouldn’t be used directly, but composed with
mailbox.Messagesub-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 byhydrate().
- box: Mailbox | None¶
The box this message was read from, kept to re-fetch its content on demand after dehydration.
- 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
AttributeErrorbefore 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:
- 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:
- 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:
- 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:
- 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:
- property parsed_date: float | None[source]¶
Parse the mail’s date header into float timestamp.
Returns
Noneif 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
Dateheader by default, or from a time of the email’s file on the filesystem: seeTimeSource.Warning
ctimedoes not refer to creation time on POSIX systems, but rather the time of the last metadata change.Note
MaildirMessage.get_date() cannot serve the
mtimesource.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 skipsget_message(). The date of such a mail is the time it was read, so themtimesource 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-thresholdcompares 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.
- 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 becomeU+FFFD, asget_payload()does with its charset, unlesserrorsnames another way out, likebackslashreplace.Encoding with
utf-8instead ofasciikeeps the non-ASCII characters of a mail parsed from a string, whichasciirejects.- Return type:
- hash_key()[source]¶
Returns the canonical hash of a mail.
Under
--raw-headers, the hash is that of the header block, asraw_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:
- 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>Fromquote 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-headerswith--hash-body rawhashes every byte.
- 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>Fromquote all count, wherehash_decoded_bodyreads 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-onlyto show. The hash itself reads the bytes of the header block: seeraw_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:
- 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:
- 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()andget_all()hand such a header over as aHeader, which string functions likeemail.utils.parsedate_tz()reject. Its text also replaces every such byte withU+FFFD, under which two headers differing in those bytes alone read, and hash, alike.- Return type:
- 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.
- 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.
- normalize_subject(subject)[source]¶
Strip
Re:/Fwd:and[list-name]prefixes fromSubject.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:
- normalize_content_type(value)[source]¶
Normalize
Content-Typeby stripping parameters.Removes everything after the semicolon, keeping only the MIME type. E.g.,
text/plain; charset=utf-8becomestext/plain.Apparently list servers actually munge
Content-Typee.g. by stripping the quotes fromcharset="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:
- normalize_date(value)[source]¶
Normalize
DatetoYYYY-MM-DDformat.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:
- normalize_address_header(value)[source]¶
Normalize address headers by removing quotes and collapsing whitespace.
E.g.,
"Bob" <bob@example.com>becomesBob <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\""becomesRobert \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:
- normalize_message_id(value)[source]¶
Normalize Message-ID header by stripping angle brackets.
E.g.,
<unique-id@example.com>becomesunique-id@example.com.- Return type:
- 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.parserstrips the<>brackets from aTo: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 usesemail.utils.unquotesomewhere 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: