xtr_mime ¶
Email messages built in code and rendered to standard MIME.
A message is put together from addresses, headers, text and HTML bodies, attachments and
inline images; Python's own email package turns it into the bytes a mail server accepts,
and DKIM or S/MIME signs it when asked.
:class:MimeTypes maps MIME types to file extensions and back, and guesses a file's type —
from its content through :class:MagicMimeTypeGuesser where libmagic is installed, from its
extension otherwise.
The parts a body is made of — :class:TextPart, :class:DataPart and the multiparts — are
usable on their own too: :class:FormDataPart is the body of an HTTP form upload.
:class:Email is the builder; :class:Message is headers over any body part, and
:class:RawMessage bytes already rendered. :class:MessageConverter reads an email back out
of a message whose body an email could have built.
:class:DefaultHtmlToTextConverter writes the text alternative of an HTML body.
HeaderKind ¶
Which kind of header :meth:Headers.set_header_body adds when the header is not there.
Address ¶
An email address and the display name shown next to it.
The address is checked against the mail grammar, international (RFC 6532) addresses included, but not against what an SMTP session accepts — the local part is not limited to 64 octets, for one: that is the envelope's and the transport's call. No DNS query is made.
Two addresses are equal when both the address and the name are: an address is a value, and a recipient list is compared and de-duplicated by value.
Check address and keep it and name, both trimmed.
Control characters are removed from the name (a tab, the one a phrase allows, stays); in the address they are refused, since one could start a new header line.
Raises:
-
InvalidArgumentError–The address contains a control character.
-
RfcComplianceError–The address is not a valid email address, or the name holds a lone surrogate — what a byte that did not decode leaves in a str.
create
classmethod
¶
Return address if it is one, else parse it from address or Name <address>.
Quotes and spaces around the name are dropped, so a name may be written "Name"
or 'Name'.
Raises:
-
InvalidArgumentError–A
<is there but noName <address>can be read. -
RfcComplianceError–The address read is not a valid email address.
-
TypeError–addressis neither an :class:Addressnor a string.
create_array
classmethod
¶
Apply :meth:create to every item, in order.
get_address ¶
Return the address as given (trimmed): an international domain stays in Unicode.
get_encoded_address ¶
Return the address with its domain written in ASCII (punycode) when it is not already.
The local part is left as it is: a non-ASCII one cannot be encoded, it needs an SMTPUTF8
session (see :meth:has_unicode_localpart). The domain was checked when the address
was built, so it always encodes; there is no silently emptied domain. A comment after a
domain literal is left out: this is the address an SMTP envelope carries.
get_encoded_name ¶
Return the display name as it is written in a header, empty when there is none.
Quoted when it holds a special character, as encoded words when it is not ASCII — the engine's choice, on one line.
Raises:
-
RfcComplianceError–The name holds an encoded word, which a reader would show decoded rather than as the text it is.
to_string ¶
Return the address as written in a header: name <address>, or the address alone.
Rendered by the engine, on one line, the domain in ASCII. An address with a non-ASCII local part is written in raw UTF-8 (RFC 6532), its name included — the form an SMTPUTF8 session carries; without SMTPUTF8 such an address cannot be sent at all.
Raises:
-
RfcComplianceError–The name holds an encoded word, which a reader would show decoded rather than as the text it is.
has_unicode_localpart ¶
Tell whether the local part holds a non-ASCII character.
Such an address can only be sent through a server that speaks SMTPUTF8 (RFC 6531), whereas a non-ASCII domain alone is written in punycode and needs nothing special.
BodyRendererInterface ¶
Bases: Protocol
Renders the body of a message from what it carries — a template and its data, say.
The mailer calls it on each message before the message is sent, so the body is built once, where the data it needs is at hand.
DkimOptions ¶
Options for :class:~xtr_mime.crypto.DkimSigner, each set by a method of its name.
An option left unset is None here and takes the signer's value: the options a signer
was built with, else its defaults — rsa-sha256, relaxed header and body
canonicalization, no body length shown, no header ignored beyond those always left out.
Start with no option set.
algorithm ¶
Set the signing algorithm: DkimSigner.ALGO_SHA256, the one supported.
body_show_length ¶
Set whether the signature says how many body octets it covers (its l= tag).
header_canon ¶
Set how headers are canonicalized: simple or relaxed.
headers_to_ignore ¶
Set the names of the headers left out of the signature, whatever their case.
From is signed even when named here: a signature must cover it.
get_body_show_length ¶
Return whether the body length is shown, None unless set.
get_header_canon ¶
Return the header canonicalization, None unless set.
get_headers_to_ignore ¶
Return the names of the headers left out, None unless set.
DkimSigner ¶
DkimSigner(private_key: str | PathLike[str], domain_name: str, selector: str, *, default_options: DkimOptions | None = None, passphrase: str = '')
Signs messages for one domain and selector, with one RSA key.
:meth:sign renders the message, hands the bytes to dkimpy and returns a new message with
the DKIM-Signature field dkimpy wrote, folded as it was signed, above every other header —
a DKIM-Signature already there included (RFC 6376, 5.6) — and the body as it was signed,
which renders the same bytes however often it is sent. The signature covers every header
of the message but Return-Path, X-Transport, an existing DKIM-Signature, those
the options name to ignore (never From) and those without a body; it does not cover
the body part's own headers (Content-Type and the like) beyond what the body hash holds.
From is listed once more than it appears, so a From added above the signed one breaks
the signature rather than being shown as its author.
Bcc is neither sent nor signed, but the message returned keeps it, so the envelope read
from that message still reaches every hidden recipient.
The signature's t= tag is read by dkimpy from the system clock — the one time xtr-mime
reads outside :mod:xtr_clock. Needs the dkim extra (xtr-mime[dkim]: dkimpy, and
cryptography to open the key).
Open the key now, so a key that does not work fails here rather than at sending.
Parameters:
-
private_key(str | PathLike[str]) –The key as PEM text, or the path to a PEM file — a path object, or a string starting with
file://. -
domain_name(str) –The signing domain, the
d=tag. -
selector(str) –The selector the public key is published under, the
s=tag. -
default_options(DkimOptions | None, default:None) –The options :meth:
signuses for whatever it is not given. -
passphrase(str, default:'') –The passphrase of an encrypted key; empty for one that is not — a passphrase given for a key that is not encrypted is refused.
Raises:
-
LogicError–The
dkimextra is not installed. -
InvalidArgumentError–The domain name or selector is not DNS labels, the key file cannot be read or its path is not one the file system accepts, or the key does not open or is not an RSA key of at least 1024 bits.
sign ¶
Return a message with the headers message is sent with, its Bcc and a DKIM-Signature.
message is left as it is; the message returned carries its body as signed — a
stream body is read here, once. options win over the signer's for each option
they set.
Raises:
-
InvalidArgumentError–The algorithm or a canonicalization is not one DKIM knows, or a header to sign has a
;in its name. -
MimeRuntimeError–The algorithm is
ed25519-sha256, which is not supported, or dkimpy refuses to sign: the message has no From to sign. -
LogicError–As rendering the message does — no author, no body to build.
-
RfcComplianceError–As rendering the message does.
SignedBody ¶
Bases: AbstractPart
A body frozen at signing: the bytes the rendered message holds, not built again.
A body is built anew at each rendering, and some do not come out the same: an attached message makes up a new Message-ID, a stream that cannot seek back is read once and is empty after; and the engine, reading those bytes back, would write some of the headers inside them otherwise. The signature covers the bytes signed, so the signed message keeps them and writes them as they are. The body's headers are the ones it was rendered with; the part takes no header added later.
The part signed is kept as well, for what reads a body's fields rather than its bytes —
:class:~xtr_mime.MessageConverter, turning the signed message back into an email.
A signer builds it; :meth:from_frozen builds it again from what one holds — a queued
message read back in another process — and it renders the same bytes there.
Freeze body as rendered — a whole message holding it — wrote it.
Raises:
-
RfcComplianceError–A header of
bodyis refused.
from_frozen
classmethod
¶
Build the body part froze as: written with headers, then body as it is.
headers are the prepared headers of a body frozen before, and body the bytes it
writes after them — what :meth:get_prepared_headers and :meth:body_to_iterable
give. part is not rendered: it is kept for what reads the body's fields.
get_signed_part ¶
Return the part the frozen bytes were rendered from.
get_prepared_headers ¶
Return a copy of the headers the body was rendered with.
SMimeEncrypter ¶
SMimeEncrypter(certificates: str | PathLike[str] | Iterable[str | PathLike[str]], cipher: str = CIPHER_AES_256_CBC)
Encrypts messages for one or several recipients, each with a certificate of its own.
:meth:encrypt renders the whole message once — its headers included — and returns a
message whose body is that rendering encrypted, an application/pkcs7-mime attachment
any recipient's key decrypts back to the very bytes rendered. The headers stay outside,
readable, so that the message can be delivered.
The certificates are read from PEM files when the encrypter is built. Needs the smime
extra (xtr-mime[smime]: cryptography), which encrypts with AES in CBC mode only: the
other CIPHER_* names are refused.
Read the recipients' certificates now, so one that does not work fails here.
Parameters:
-
certificates(str | PathLike[str] | Iterable[str | PathLike[str]]) –The path of a recipient's PEM certificate, or the paths of several; a string may start with
file://. -
cipher(str, default:CIPHER_AES_256_CBC) –The cipher the message is encrypted with, one of the
CIPHER_*names cryptography supports:aes-128-cbcoraes-256-cbc.
Raises:
-
LogicError–The
smimeextra is not installed. -
InvalidArgumentError–The cipher is unknown or not supported, no certificate is given, or one or its key does not load, or its key is not RSA.
-
MimeRuntimeError–A file does not exist or cannot be read, or a path is not one the file system accepts.
encrypt ¶
Return a message with the headers of message and the whole of it encrypted.
message is left as it is, rendered here once, as it is sent: without Bcc. A Date or
Message-ID that sending adds is added to the headers returned too, so the message
delivered names the one it holds.
Raises:
-
LogicError–As rendering the message does.
-
RfcComplianceError–As rendering the message does.
SMimeSigner ¶
SMimeSigner(certificate: str | PathLike[str], private_key: str | PathLike[str], *, passphrase: str = '', extra_certificates: str | PathLike[str] | None = None, algorithm: str = ALGO_SHA256)
Signs messages with one certificate and its private key, the signature detached.
:meth:sign renders the message's body once and returns a message whose body is a
multipart/signed part: the body as it was signed, then the signature — readable by a
client that cannot check it. The message's headers stay outside the signature, as they are.
The certificates and the key are read from PEM files when the signer is built. Needs the
smime extra (xtr-mime[smime]: cryptography).
Read the certificate and open the key now, so one that does not work fails here.
Parameters:
-
certificate(str | PathLike[str]) –The path of the signing certificate's PEM file; a string may start with
file://. -
private_key(str | PathLike[str]) –The path of the PEM file of the certificate's private key, RSA or EC. An RSA key has at least 1024 bits, and its certificate is not for RSA-PSS: the signature is made with PKCS #1 v1.5 padding.
-
passphrase(str, default:'') –The passphrase of an encrypted key; empty for one that is not — a passphrase given for a key that is not encrypted is refused.
-
extra_certificates(str | PathLike[str] | None, default:None) –The path of a PEM file of the intermediate certificates a receiver needs to follow the signing certificate up to one it trusts.
-
algorithm(str, default:ALGO_SHA256) –The digest signed, one of the
ALGO_*names.
Raises:
-
LogicError–The
smimeextra is not installed. -
InvalidArgumentError–The algorithm is not one of the
ALGO_*names, a certificate or the key does not load, the key is neither RSA nor EC, an RSA key is shorter than 1024 bits or certified for RSA-PSS, or the key is not the certificate's. -
MimeRuntimeError–A file does not exist or cannot be read, or a path is not one the file system accepts.
sign ¶
Return a message with the headers of message and its body signed.
message is left as it is; a stream body is read here, once. A message without a
body is signed with the empty text it renders with. A Date or Message-ID that sending
adds is added to the headers returned too — the Date read from the clock of
message — so the signed message renders the same every time.
Raises:
-
LogicError–As rendering the body does, or the message has neither a From nor a Sender to send it with.
-
RfcComplianceError–As rendering the body does.
DraftEmail ¶
DraftEmail(headers: Headers | None = None, body: AbstractPart | None = None, *, clock: ClockInterface | None = None)
Bases: Email
An email marked X-Unsent: 1, which a mail client opens as a draft to send.
It needs no author, date or identifier — the client that sends it adds them — so its
prepared headers add only MIME-Version. Being a draft, it is never valid to send.
Start as an email does, marked as unsent.
get_prepared_headers ¶
Return a copy of the headers with MIME-Version added and Bcc taken out.
Email ¶
Email(headers: Headers | None = None, body: AbstractPart | None = None, *, clock: ClockInterface | None = None)
Bases: Message
An email built with chained calls, its body put together from what was given.
The body is a text part, an HTML part or both (multipart/alternative); attachments the
HTML shows through cid: sit next to it (multipart/related) and the others after it
(multipart/mixed). It is put together when first asked for and kept until the text,
the HTML or the attachments change, so a signature and the message sent see the same
boundaries. A body set with :meth:set_body is sent as it is instead.
Start with a copy of headers and, if given, a body sent as it is.
sender ¶
Set the Sender, who sent the email on behalf of its authors.
from_ ¶
reply_to ¶
Set the addresses replies go to, replacing any set.
bcc ¶
Set the hidden recipients, replacing any set; no recipient sees them.
priority ¶
Set X-Priority, from 1 (highest) to 5 (lowest); a value outside is brought inside.
get_priority ¶
Return the priority X-Priority starts with, normal (3) when it starts with none.
text ¶
Set the text body, in charset; None takes it away.
Raises:
-
TypeError–bodyis not a string, bytes, a binary file orNone.
get_text_charset ¶
Return the charset of the text body, None unless set.
html ¶
Set the HTML body, in charset; None takes it away.
Raises:
-
TypeError–bodyis not a string, bytes, a binary file orNone.
get_html_charset ¶
Return the charset of the HTML body, None unless set.
attach ¶
Attach content, application/octet-stream unless content_type says otherwise.
attach_from_path ¶
attach_from_path(path: str | PathLike[str], name: str | None = None, content_type: str | None = None) -> Self
Attach a file, read when the email is rendered; its extension gives its type.
embed ¶
Attach content shown inside the body: cid:<name> in the HTML refers to it.
embed_from_path ¶
embed_from_path(path: str | PathLike[str], name: str | None = None, content_type: str | None = None) -> Self
Attach a file shown inside the body: cid:<name> in the HTML refers to it.
get_attachments ¶
Return the attachments, in order; changing the list leaves the email as it is.
get_body ¶
Return the body set, else the one put together from the text, HTML and attachments.
Raises:
-
LogicError–There is no body set, no text, no HTML and no attachment.
-
InvalidArgumentError–The HTML body is bytes in a charset Python does not know.
ensure_validity ¶
Check the email has a body, is not a draft, and names a recipient and an author.
Raises:
-
LogicError–One of those is missing, or X-Unsent marks the email as a draft.
InvalidArgumentError ¶
Bases: MimeError, ValueError
A value handed to this library cannot be used: an unknown charset, an unreadable path.
Also a :class:ValueError, so code that already guards against a bad value catches it
without knowing this library exists.
LogicError ¶
Bases: MimeError, RuntimeError
This library was used in a way that cannot work, whatever the values involved.
A message with no body, a part asked for something only another kind of part has: each is a mistake in the calling code, so trying again changes nothing.
MimeError ¶
Bases: Exception
A message could not be built or rendered — catch this to catch them all.
MimeRuntimeError ¶
Bases: MimeError, RuntimeError
Something outside the calling code failed: a file that vanished, a key that would not load.
The values handed in were fine and so is the code; the world did not cooperate.
RfcComplianceError ¶
Bases: InvalidArgumentError
A value breaks the rules of the mail standards, so no server would accept it.
An address that is not one, a domain that cannot be written in ASCII, a header parameter
name that is not a token. A kind of :class:InvalidArgumentError, kept apart so a caller
validating user input can tell "not an email address" from any other bad value.
Group ¶
A display name over a list of addresses, written name: a, b; (RFC 5322, 3.4).
A group goes wherever a list of addresses does. With no member it says who received the
message without naming anyone — To: undisclosed-recipients:;. In From (RFC 6854 allows
it, for limited use) it leaves the message without an author address, which the Message-ID
and the SMTP envelope need: set a Sender next to it.
Keep name, trimmed and without control characters, and create the members.
Raises:
-
InvalidArgumentError–nameis empty once cleaned: a group is written by its name. -
RfcComplianceError–nameholds a lone surrogate — what a byte that did not decode leaves in a str — or a member is not a valid email address.
AbstractHeader ¶
A header with a checked name, rendered by the engine from the value it holds.
A subclass says what its body is and which engine value writes it; encoding and folding are the engine's. The charset, language and line length are kept for the code that reads them, but the engine writes every encoded word and parameter in UTF-8, without a language, folded at 76 columns.
A name may hold a colon (h:Sender): such a header exists only for a transport that
reads it as a form field, through :meth:get_body_as_string. A reader ends a name at its
first colon — Bcc:victim@example.com,x would be read as a Bcc header — so
:meth:to_string refuses it, and no message carries it.
Keep name once checked.
It is checked here, not when the header is written: a header with a line break in its name would start a header of its own.
Raises:
-
RfcComplianceError–nameis not printable ASCII, or holds a space.
set_body
abstractmethod
¶
Replace the body, once checked to be of the type this header holds.
Raises:
-
InvalidArgumentError–bodyis not of that type.
set_language ¶
Set the language of the body, an RFC 5646 tag such as en-us.
set_max_line_length ¶
Set the line length the header is meant to be folded at.
to_string ¶
Return the whole field as the engine writes it, folded, without the final CRLF.
Raises:
-
RfcComplianceError–The name holds a colon, or the engine refuses the value: a control character, an address that would not read back, a parameter or identifier the grammar refuses.
get_body_as_string ¶
Return the body as the engine writes it, joined back onto one line, whatever the name.
Raises:
-
RfcComplianceError–The engine refuses the value, as :meth:
to_stringsays.
to_field ¶
Return the field as :meth:to_string writes it, None when it has no body.
What :class:Headers renders a header with: the value is folded once for both, where
asking :meth:get_body_as_string then :meth:to_string folds it twice. A subclass
that writes itself its own way is rendered through those two methods instead.
Raises:
-
RfcComplianceError–As :meth:
to_stringdoes, for a header with a body.
DateHeader ¶
Bases: AbstractHeader
A header whose body is a date, written in RFC 5322 form at the date's own UTC offset.
The offset is kept, not converted to UTC: it tells the reader the sender's local time.
A date without one is written -0000, which RFC 5322 reads as "offset unknown".
Keep name and date_time.
Raises:
-
RfcComplianceError–nameis not a header name.
set_body ¶
FoldedHeader ¶
Bases: UnstructuredHeader
A text header kept as the field it was given, folding and all, and written as it is.
The engine folds every header it writes its own way. A field folded elsewhere — the
DKIM-Signature a signer wrote, which simple header canonicalization hashes byte for
byte — would no longer be the same bytes refolded, so it is written as given. Its value is
the field unfolded; setting another value drops the folding, and the engine writes that one.
Keep field, Name: value folded with CRLF, once checked to be one header.
Raises:
-
RfcComplianceError–The name is not a header name, or a line of the field would start a header of its own, holds a control character or is longer than 998 octets.
HeaderInterface ¶
Bases: Protocol
One header field: a name, a typed body, and the text it is written as.
The body's type depends on the header — text, an address, a list of addresses, a date,
identifiers — so :meth:get_body and :meth:set_body deal in object, and each class
checks what it is given. The typed accessors of each class are the ones to call when the
class is known.
set_body ¶
Replace the body; the type depends on the header.
Raises:
-
InvalidArgumentError–bodyis not of the type this header holds.
set_language ¶
Set the language of the body, an RFC 5646 tag such as en-us.
set_max_line_length ¶
Set the line length the header is meant to be folded at.
to_string ¶
Return the whole field as written in a message, folded, without the final CRLF.
get_body_as_string ¶
Return the body as written in a message, encoded but on one line.
Headers ¶
Headers in the order they were added, looked up by name whatever its case.
Adding checks two rules: a header named in the class map must be of its class (a From is a list of addresses, never text), and a header a message carries once cannot be added twice.
Add headers, in order.
Raises:
-
LogicError–A header is not of the class its name needs, or is added twice when it must be unique.
set_max_line_length ¶
Set the line length on every header, and on every header added later.
add_mailbox_list_header ¶
Add a list of addresses and groups; a string is read as an address.
add_mailbox_header ¶
Add one address; a string may be Name <address>.
add_id_header ¶
Add one identifier or several.
add_path_header ¶
Add a path; a string is the bare address.
add_parameterized_header ¶
add_parameterized_header(name: str, value: str, parameters: Mapping[str, str | None] | None = None) -> Self
Add a value with parameters.
add_header ¶
Add a header of the class its name needs, text for a name the map does not know.
For an address list or identifiers, argument is one value or a sequence of them,
and more adds values after it; any other header takes argument alone.
Raises:
-
InvalidArgumentError–A value is not of the type the header takes.
add ¶
Add header after the others, with this collection's line length.
Raises:
-
LogicError–headeris not of the class its name needs, or it must be unique and one of its name is already there.
get ¶
Return the first header of that name, whatever its case, None if there is none.
all ¶
Yield every header in order, or every header of one name, whatever its case.
get_names ¶
Return the names, lowercased, in the order they were first added.
is_unique_header
staticmethod
¶
Tell whether a message carries a header of that name at most once.
check_header_class
staticmethod
¶
Check that header is of the class its name needs, if the class map names one.
Raises:
-
LogicError–It is not.
to_array ¶
Return every header with a body as its folded field; one without a body is skipped.
get_header_body ¶
Return the body of the first header of that name, None if there is none.
set_header_body ¶
Replace the body of the first header of that name, or add one of kind.
Raises:
-
InvalidArgumentError–bodyis not of the type the header takes.
get_header_parameter ¶
Return a parameter of the first header of that name, None if there is none.
Raises:
-
LogicError–The header is not a :class:
ParameterizedHeader.
set_header_parameter ¶
Set a parameter of the first header of that name.
Raises:
-
LogicError–There is no such header, or it is not a :class:
ParameterizedHeader.
IdentificationHeader ¶
Bases: AbstractHeader
A header whose body is one or more identifiers, each written <id>.
An identifier is an RFC 5322 msg-id, id-left@id-right, not a mail address: its right
side may hold atoms no domain does. A right side outside ASCII is written in punycode.
Keep name and the identifiers, without their angle brackets.
Raises:
-
RfcComplianceError–nameis not a header name, or an identifier is not a msg-id.
set_body ¶
Replace the identifiers with body, one or a sequence of them.
Raises:
-
InvalidArgumentError–bodyis neither a string nor a sequence of strings. -
RfcComplianceError–An identifier is not a msg-id.
set_id ¶
Replace the identifiers with one, or with several.
Raises:
-
RfcComplianceError–An identifier is not a msg-id.
set_ids ¶
MailboxHeader ¶
Bases: AbstractHeader
A header whose body is one address, written name <address> or the address alone.
Keep name and address.
Raises:
-
RfcComplianceError–nameis not a header name.
set_body ¶
MailboxListHeader ¶
Bases: AbstractHeader
A header whose body is an address list: each entry an address or a group of them.
Groups (RFC 6854 allows them even in From) are kept as given in :meth:get_address_list;
:meth:get_addresses — the body — lists every mailbox, group members included, since that
is who the message goes to.
Keep name and the address list.
Raises:
-
RfcComplianceError–nameis not a header name.
create_address_list
staticmethod
¶
Turn every entry that is not already an address or a group into an address.
Raises:
-
InvalidArgumentError–A string has a
<but noName <address>can be read. -
RfcComplianceError–A string is not a valid email address.
set_body ¶
Replace the address list.
Raises:
-
InvalidArgumentError–bodyis not a sequence of addresses and groups.
set_addresses ¶
Replace the address list.
add_addresses ¶
Append to the address list, in order.
add_address ¶
Append one address or group to the address list.
get_addresses ¶
Return every mailbox, group members included, in order.
get_address_list ¶
Return the address list as given: addresses and groups.
get_address_strings ¶
Return each entry as written in the header, on one line.
Raises:
-
RfcComplianceError–The engine refuses an entry, such as a name holding an encoded word.
ParameterizedHeader ¶
Bases: UnstructuredHeader
A header written value; name="value", as Content-Type and Content-Disposition are.
A parameter that is not ASCII, or too long for a line, is written in RFC 2231 form by the
engine. A parameter set to None is kept but not written.
Keep name, value and parameters.
Raises:
-
RfcComplianceError–nameis not a header name, or a parameter name is not a token or is longer than 40 characters.
set_parameter ¶
Set one parameter, replacing it if it is there; None keeps it unwritten.
Raises:
-
RfcComplianceError–parameteris not a token or is longer than 40 characters.
get_parameter ¶
Return a parameter's value, empty when it is not set or set to None.
set_parameters ¶
Replace every parameter.
Raises:
-
RfcComplianceError–A parameter name is not a token or is longer than 40 characters; the parameters are then left as they were.
PathHeader ¶
Bases: AbstractHeader
A header whose body is an address written <address> (RFC 5322, 3.6.7).
A path has no display name: the address's name, if it has one, is not written. The domain is written in punycode; a non-ASCII local part is written as raw UTF-8, the form an SMTPUTF8 session carries, as in an address header.
Keep name and address.
Raises:
-
RfcComplianceError–nameis not a header name.
set_body ¶
UnstructuredHeader ¶
Bases: AbstractHeader
A header whose body is text, written as it is or as encoded words when it is not ASCII.
Open to subclassing: a header with a name and a meaning of its own but a text body — a tag, a piece of metadata — is one of these.
Keep name and the text value.
Raises:
-
RfcComplianceError–nameis not a header name.
set_body ¶
DefaultHtmlToTextConverter ¶
Strips the tags of an HTML body, keeping the text a reader would see.
The head, scripts and styles are dropped with what they hold, comments and declarations
vanish, and character references are decoded; a numeric one past U+10FFFF, however many
digits it is written with, reads as U+FFFD. Whitespace is collapsed: each line is trimmed
and a run of whitespace inside it becomes one space, runs of blank lines become one blank
line, and the whole text is trimmed, so the indentation of a <pre> block is lost. An
element that is opened but never closed hides nothing: its text is kept.
The HTML is read by the standard library's tolerant parser, so malformed or hostile markup converts without an error, in time that grows with its length.
HtmlToTextConverterInterface ¶
Bases: Protocol
Writes the text a plain-text mail reader shows in place of an HTML body.
A message with only an HTML body reads poorly, or not at all, where HTML is not rendered; a converter derives the text alternative from the HTML, so the two never say different things.
convert ¶
Return the text html reads as.
charset is the charset the HTML body is sent in, and the text body is sent in the
same one.
MagicMimeTypeGuesser ¶
Bases: MimeTypeGuesserInterface
Reads a file's first bytes and names its type, as the file command does.
A file's name says what someone called it; its bytes say what it is, which is what matters for, say, an upload claiming to be an image. libmagic keeps the signatures that tell.
Needs the magic extra (xtr-mime[magic], which brings python-magic) and libmagic
itself, which no wheel ships: brew install libmagic, apt install libmagic1. Without
either, :meth:is_guesser_supported answers False and :class:~xtr_mime.MimeTypes
asks its other guessers. Nothing is loaded before that first question, so building one
costs nothing and importing this package never needs the extra.
Build a guesser that loads libmagic the first time it is asked whether it can run.
is_guesser_supported ¶
Tell whether python-magic and libmagic load, trying once per guesser.
A failed load is not retried: on some hosts finding libmagic runs a program, and
:class:~xtr_mime.MimeTypes asks before every guess.
guess_mime_type ¶
Name the type libmagic reads in the file at path.
Returns:
-
str | None–The MIME type, or
Nonewhen libmagic answers nothing.
Raises:
-
InvalidArgumentError–When
pathdoes not name a file this process may read. -
LogicError–When python-magic or libmagic does not load.
-
MimeRuntimeError–When libmagic fails, its database missing or unreadable; libmagic's own error is its cause.
Message ¶
Message(headers: Headers | None = None, body: AbstractPart | None = None, *, clock: ClockInterface | None = None)
Bases: RawMessage
Headers and a body part, rendered to MIME when sent.
:meth:get_headers holds what the caller set; :meth:get_prepared_headers adds to a copy
what sending needs — MIME-Version, Date from the clock, Message-ID, From
from Sender or Sender from the first of several From — and leaves Bcc out,
which no recipient may see. A message with no body is sent with an empty text one.
Keep a copy of headers, body itself, and the clock the Date is read from.
set_headers ¶
Replace the headers with headers itself, not a copy.
get_headers ¶
Return the headers the caller set, which the caller may change.
get_prepared_headers ¶
Return a copy of the headers with what sending needs added and Bcc taken out.
Raises:
-
LogicError–There is neither a From nor a Sender, or From names no address to make a Message-ID from.
to_string ¶
Render the message: its prepared headers, then its body.
Raises:
-
LogicError–As :meth:
get_prepared_headersdoes, or the body cannot be built. -
InvalidArgumentError–A body cannot be read or written as asked.
-
RfcComplianceError–A header is refused.
to_iterable ¶
Render the message in the pieces the engine writes, as a mail server receives them.
Raises:
-
LogicError–As :meth:
to_stringdoes. -
InvalidArgumentError–As :meth:
to_stringdoes. -
RfcComplianceError–As :meth:
to_stringdoes.
ensure_validity ¶
Check the message names a recipient and an author.
Raises:
-
LogicError–No To, Cc or Bcc names anyone, or neither From nor Sender is set.
generate_message_id ¶
Make up a Message-ID: 32 random hex digits at the domain of the sender.
The sender is Sender, else the first address of From; an international domain is written in ASCII, as the header carries it.
Raises:
-
LogicError–There is neither a From nor a Sender, or From names no address.
MessageConverter ¶
Reads an email's text, HTML and attachments back out of a message's body tree.
A transport that hands a provider's API fields — not MIME — needs them. Only the trees an
email builds are understood: a text or HTML part, both in alternative, inside
related with inline parts, inside mixed with attachments.
A message signed with DKIM is read from the part its signature was made over, so the email carries the same text, HTML and attachments. A body signed or encrypted with S/MIME is refused: its fields cannot be handed over apart from the signature or the encryption.
to_email
staticmethod
¶
Return message if it is an email, else an email with its headers and body.
Raises:
-
MimeRuntimeError–The body is not a tree an email builds, or is signed or encrypted with S/MIME.
MimeTypeGuesserInterface ¶
Bases: Protocol
Guesses the MIME type of the file at a path.
A guesser may need something the host lacks — a native library, a command — so it tells
whether it can run before it is asked, and :class:~xtr_mime.MimeTypes asks only the
guessers that can.
is_guesser_supported ¶
Tell whether this guesser can run on this host.
guess_mime_type ¶
Name the MIME type of the file at path.
Returns:
-
str | None–The MIME type, or
Nonewhen this guesser cannot tell.
Raises:
-
InvalidArgumentError–When
pathdoes not name a file this process may read. -
LogicError–When this guesser cannot run on this host.
MimeTypes ¶
Bases: MimeTypesInterface
Maps MIME types to extensions and back, and guesses the MIME type of a file.
The table is the standard library's built-in one (mimetypes.MimeTypes()): its registered
types first, then the common unregistered ones (image/jpg after image/jpeg). It is
deliberately not the module-level database, which also reads the host's mime.types
files: a message must not change with the machine that renders it. An extra map adds types
or extensions the table lacks, and ranks before it. A lookup that finds nothing as written
tries again in lower case.
To guess a file's type, the registered guessers that can run here are asked, the last
registered first, and the first answer wins. A new table registers a
:class:~xtr_mime.MagicMimeTypeGuesser, which reads the file's content where libmagic is
installed. When no guesser answers, the file's extension is looked up in the table — so,
unlike a guesser that needs a native library, this one can always guess, but without
libmagic it names a file by what it is called, not by what it holds.
:meth:get_default keeps one shared table for code that has none handed to it; it is the
only state shared between instances.
Build the table, extra_map first, and register the libmagic guesser.
Parameters:
-
extra_map(Mapping[str, Sequence[str]] | None, default:None) –Extensions by MIME type, without their leading dot, ranked before the standard table's:
{"application/mbox": ["mbox"]}.
get_default
classmethod
¶
Return the shared table, built on first use unless :meth:set_default gave one.
set_default
classmethod
¶
Make default the table :meth:get_default returns from now on.
register_guesser ¶
Ask guesser before every guesser registered so far, the libmagic one included.
get_extensions ¶
Return the extensions of files of mime_type, the preferred one first.
get_mime_types ¶
Return the MIME types of files ending in extension, the preferred one first.
is_guesser_supported ¶
Answer True: the table answers whenever no registered guesser can.
guess_mime_type ¶
Name the type of the file at path: its guessers' answer, else its extension's.
Returns:
-
str | None–The MIME type, or
Nonewhen no guesser answers and the table does not know the -
str | None–file's extension.
Raises:
-
InvalidArgumentError–When
pathdoes not name a file this process may read.
MimeTypesInterface ¶
Bases: MimeTypeGuesserInterface, Protocol
A table of MIME types and the extensions files of each type end in.
Several extensions can share a type and several types an extension, so both lookups answer a list, the preferred entry first: the first extension is the one to give a file of that type, the first type the one to send a file with that extension as. Extensions are written without their leading dot.
get_extensions ¶
AbstractMultipartPart ¶
Bases: AbstractPart
A multipart/* part: other parts, each opened by a boundary line.
The boundary is made up once per part — eight URL-safe characters from six random bytes — and given to the engine, which never picks one of its own.
Keep parts, in order.
AbstractPart ¶
A MIME part: headers, a blank line, a body.
:meth:get_headers holds what the caller adds; :meth:get_prepared_headers adds what the
part itself decides — its media type above all — to a copy, so rendering never changes
the part. A subclass says what its media type is and how the engine builds it.
Start with no headers of the caller's.
set_content_type_parameter ¶
Set a parameter of Content-Type, such as method for text/calendar.
Raises:
-
RfcComplianceError–nameis not a token or is longer than 40 characters.
get_prepared_headers ¶
Return a copy of the headers with what the part decides set on it.
Changing the copy leaves the part as it is.
to_string ¶
Render the part: its prepared headers, a blank line, its encoded body.
Bytes that are not UTF-8 (an 8bit body) survive as surrogates, as
:meth:to_iterable writes them.
Raises:
-
InvalidArgumentError–The body cannot be read or written as asked.
-
RfcComplianceError–A header is refused.
to_iterable ¶
Render the part in the pieces the engine writes, as a mail server receives them.
Raises:
-
InvalidArgumentError–As :meth:
to_stringdoes. -
RfcComplianceError–As :meth:
to_stringdoes.
body_to_string ¶
Render the encoded body alone, as :meth:to_string writes it.
body_to_iterable ¶
Render the encoded body alone, as :meth:to_iterable writes it.
get_media_type
abstractmethod
¶
Return the media type, the part of Content-Type before the slash.
get_media_subtype
abstractmethod
¶
Return the media subtype, the part of Content-Type after the slash.
AlternativePart ¶
Bases: AbstractMultipartPart
The same content in several forms, the one a reader prefers last: text, then HTML.
DataPart ¶
DataPart(body: str | bytes | BinaryIO | File, filename: str | None = None, content_type: str | None = None, encoding: str | None = None)
Bases: TextPart
Bytes with a content type and a filename, attached unless :meth:as_inline is called.
Its content id is made up the first time it is asked for, unless one was set: an HTML
body refers to an inline image by it, cid:<id>.
Keep the body, its filename and its type/subtype.
A :class:File names the part and gives its type unless filename and
content_type say otherwise; anything else is application/octet-stream.
Raises:
-
TypeError–bodyis none of the types a body may be. -
InvalidArgumentError–As :class:
TextPartraises it.
from_path
staticmethod
¶
from_path(path: str | PathLike[str], name: str | None = None, content_type: str | None = None, encoding: str | None = None) -> DataPart
Build a part from a file read when the part is rendered.
Raises:
-
InvalidArgumentError–pathis a directory or a file this process may not read, orencodingis not one the part knows.
set_content_id ¶
Set the content id, left@right without angle brackets.
Raises:
-
InvalidArgumentError–content_idholds no@.
get_content_id ¶
Return the content id, made up now if none was set or made up before.
get_prepared_headers ¶
Return the text part's headers with the content id and the filename added.
as_debug_string ¶
Describe the part: the text part's description and the filename.
DigestPart ¶
Bases: AbstractMultipartPart
Messages gathered into one, as a mailing list digest is; every part is a message.
Keep the messages, in order.
File ¶
A path, with the name and type an attachment of it gets.
Nothing is read when the file is named: a part built from it reads it when rendered, so an email holding large attachments costs nothing until it is sent.
Keep path and the name to show for it, its base name when None.
FormDataPart ¶
Bases: AbstractMultipartPart
A form: each field a part named in its Content-Disposition, as a browser sends it.
A string becomes a UTF-8 text field; a :class:TextPart or :class:DataPart is copied
and named after its field, the given part left as it is; nested fields are named
name[key]. A field without an explicit transfer encoding is written in 8bit, its
bytes as they are — RFC 7578, 4.7 deprecates the header; an explicit one is kept for the
receivers that ask for it.
This is HTTP, not mail: the form writes its fields itself. A field name or filename is
raw UTF-8 with ", CR and LF escaped as browsers do, never in RFC 2231 form, and no
header is folded. :meth:get_prepared_headers and :meth:body_to_iterable are the HTTP
request's Content-Type and body.
Read the fields and their names.
Raises:
-
InvalidArgumentError–A value is not a string, a part or nested fields, or a top-level integer key holds other than a single field.
get_parts ¶
Return a part per field, named after it, with the form-data disposition.
to_string ¶
Render the Content-Type header, a blank line and the body.
Raises:
-
InvalidArgumentError–A field's body cannot be read or written as asked.
-
RfcComplianceError–A header would hold a line break, a NUL or a lone surrogate.
to_iterable ¶
Render the Content-Type header, a blank line and the body, in pieces.
Raises:
-
InvalidArgumentError–As :meth:
to_stringdoes. -
RfcComplianceError–As :meth:
to_stringdoes.
body_to_string ¶
Render the body; bytes that are not UTF-8 survive as surrogates.
body_to_iterable ¶
Render the body, field by field: what an HTTP client sends.
Raises:
-
InvalidArgumentError–A field's body cannot be read or written as asked.
-
RfcComplianceError–A header would hold a line break, a NUL or a lone surrogate.
MessagePart ¶
Bases: DataPart
A message carried as an attachment, named after its subject (email.eml for none).
The message is rendered when the part is, and written in 8bit: RFC 2046 allows a
message/rfc822 body only 7bit, 8bit or binary, so a reader opens it as the
message it is. Its bytes are written as they are, 8-bit ones included, but for its line
ends, every one written as CRLF — the only line end SMTP carries; the message itself is
left as it is.
Keep message; it is rendered only when the part is.
MixedPart ¶
Bases: AbstractMultipartPart
Independent parts shown one after the other: the body first, then the attachments.
RelatedPart ¶
Bases: AbstractMultipartPart
A main part — an HTML body — followed by the parts it shows, found by content id.
Every part after the main one is given a Content-ID header if it has none, so the main part has something to refer to.
Keep the main part first, then the others, giving each a content id it lacks.
SMimePart ¶
Bases: AbstractPart
A body written as it is given, under a media type and Content-Type parameters.
A signature covers bytes: the body of a multipart/signed part, its boundaries and the
signed part inside, must reach the receiver exactly as they were signed. The body is kept
as the bytes given, a bare line feed turned into CRLF once, and written as they are every
time the part renders — never read back by the engine, which would write some of the
headers inside it otherwise.
Keep the body, already encoded, and the Content-Type it is written under.
Parameters:
-
body(str | bytes) –The body as it is sent, after the blank line ending the headers.
-
media_type(str) –The part of Content-Type before the slash.
-
media_subtype(str) –The part of Content-Type after the slash.
-
parameters(Mapping[str, str]) –The Content-Type parameters,
boundaryfor a multipart.
get_prepared_headers ¶
Return a copy of the headers with Content-Type and its parameters set on it.
TextPart ¶
TextPart(body: str | bytes | BinaryIO | File, charset: str | None = 'utf-8', subtype: str = 'plain', encoding: str | None = None)
Bases: AbstractPart
A part holding one body: text in a charset, or bytes when the charset is None.
The body is a string, bytes, a binary file or a :class:File; a file is read each time
the part is rendered, a seekable one from its start. Without an explicit transfer
encoding, one is chosen when rendering: 8bit for a form field, base64 for bytes
with no charset, quoted-printable for text. In a mail, 8bit and binary bodies
have their line breaks written as CRLF, the only line end SMTP carries.
Keep the body, its charset and subtype, and the transfer encoding asked for.
Raises:
-
TypeError–bodyis none of the types a body may be. -
InvalidArgumentError–bodyis a :class:Filenaming a directory or a file this process may not read, orencodingis not one the part knows.
set_disposition ¶
Set how the part is shown: attachment, inline or form-data.
get_body ¶
Return the body before transfer encoding: a string as given, bytes otherwise.
Raises:
-
InvalidArgumentError–The body is a :class:
Filethat cannot be read.
get_prepared_headers ¶
Return the headers with Content-Type, its charset and name, and the encoding set.
A form field carries its name in Content-Disposition only.
as_debug_string ¶
Describe the part: its media type, charset and disposition.
RawMessage ¶
A message sent as the bytes it already is, nothing parsed or added.
The content is a string (sent as UTF-8), bytes, a binary file (read from its start, line by line, each time it is sent; whoever opened it closes it) or chunks of bytes. An iterator of chunks — a generator — can be read once: what it yields is kept as it goes, so a message read to its end can be sent again, and one left half read cannot.
A copy reads the same iterator as the message it copies: the bytes one of them read to the end are there for every other, and a read one of them left half done — or is still doing — leaves every other unable to read.
A string may carry bytes that are not UTF-8 as the surrogates :meth:to_string gives them
as; any other lone surrogate has no bytes to be sent as, and the message is refused.
Keep message; nothing is read until the message is.
to_string ¶
Return the whole message as text; bytes that are not UTF-8 survive as surrogates.
A string is checked as sending it would be: what this returns is the text of what is sent, and a string that cannot be sent has none.
Raises:
-
LogicError–The message is a generator that was left half read.
-
InvalidArgumentError–The message is a string UTF-8 cannot hold.
to_iterable ¶
Yield the message in the pieces it is held in, as a mail server receives them.
Closing the generator before its end leaves a message held as a generator unreadable.
Raises:
-
LogicError–The message is a generator that was left half read.
-
InvalidArgumentError–The message is a string UTF-8 cannot hold.
ensure_validity ¶
Check the message can be sent; a raw message always can.
Raises:
-
LogicError–In a subclass, the message cannot be sent as it is.