Skip to content

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

HeaderKind = Literal['text', 'parameterized', 'mailbox', 'mailbox_list', 'date', 'id', 'path']

Which kind of header :meth:Headers.set_header_body adds when the header is not there.

Address

Address(address: str, name: str = '')

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

create(address: Address | str) -> Address

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:

create_array classmethod

create_array(addresses: Iterable[Address | str]) -> list[Address]

Apply :meth:create to every item, in order.

get_address

get_address() -> str

Return the address as given (trimmed): an international domain stays in Unicode.

get_name

get_name() -> str

Return the display name, empty when there is none.

get_encoded_address

get_encoded_address() -> str

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

get_encoded_name() -> str

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

to_string() -> str

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

has_unicode_localpart() -> bool

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.

render

render(message: Message) -> None

Fill in the body of message, changing it in place.

DkimOptions

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

algorithm(algorithm: str) -> Self

Set the signing algorithm: DkimSigner.ALGO_SHA256, the one supported.

body_show_length

body_show_length(show: bool) -> Self

Set whether the signature says how many body octets it covers (its l= tag).

header_canon

header_canon(canon: str) -> Self

Set how headers are canonicalized: simple or relaxed.

body_canon

body_canon(canon: str) -> Self

Set how the body is canonicalized: simple or relaxed.

headers_to_ignore

headers_to_ignore(headers: Iterable[str]) -> Self

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_algorithm

get_algorithm() -> str | None

Return the signing algorithm, None unless set.

get_body_show_length

get_body_show_length() -> bool | None

Return whether the body length is shown, None unless set.

get_header_canon

get_header_canon() -> str | None

Return the header canonicalization, None unless set.

get_body_canon

get_body_canon() -> str | None

Return the body canonicalization, None unless set.

get_headers_to_ignore

get_headers_to_ignore() -> tuple[str, ...] | None

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:sign uses 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 dkim extra 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

sign(message: Message, options: DkimOptions | None = None) -> Message

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

SignedBody(body: AbstractPart, rendered: bytes)

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:

from_frozen classmethod

from_frozen(part: AbstractPart, headers: Headers, body: bytes) -> Self

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

get_signed_part() -> AbstractPart

Return the part the frozen bytes were rendered from.

get_prepared_headers

get_prepared_headers() -> 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-cbc or aes-256-cbc.

Raises:

  • LogicError –

    The smime extra 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

encrypt(message: Message) -> Message

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:

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 smime extra 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

sign(message: Message) -> Message

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

get_prepared_headers() -> 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.

subject

subject(subject: str) -> Self

Set the Subject.

get_subject

get_subject() -> str | None

Return the Subject, None unless set.

date

date(date_time: datetime) -> Self

Set the Date; sending sets it from the clock otherwise.

get_date

get_date() -> datetime | None

Return the Date, None unless set.

return_path

return_path(address: Address | str) -> Self

Set the Return-Path, where a bounce goes.

get_return_path

get_return_path() -> Address | None

Return the Return-Path, None unless set.

sender

sender(address: Address | str) -> Self

Set the Sender, who sent the email on behalf of its authors.

get_sender

get_sender() -> Address | None

Return the Sender, None unless set.

add_from

add_from(*addresses: Address | str) -> Self

Add authors after those already set.

from_

from_(*addresses: Address | str) -> Self

Set the authors, replacing any set.

Raises:

get_from

get_from() -> list[Address]

Return the authors, group members included.

add_reply_to

add_reply_to(*addresses: Address | str) -> Self

Add addresses replies go to.

reply_to

reply_to(*addresses: Address | str) -> Self

Set the addresses replies go to, replacing any set.

get_reply_to

get_reply_to() -> list[Address]

Return the addresses replies go to.

add_to

add_to(*addresses: Address | str) -> Self

Add recipients.

to

to(*addresses: Address | str) -> Self

Set the recipients, replacing any set.

get_to

get_to() -> list[Address]

Return the recipients, group members included.

add_cc

add_cc(*addresses: Address | str) -> Self

Add recipients of a copy.

cc

cc(*addresses: Address | str) -> Self

Set the recipients of a copy, replacing any set.

get_cc

get_cc() -> list[Address]

Return the recipients of a copy.

add_bcc

add_bcc(*addresses: Address | str) -> Self

Add hidden recipients.

bcc

bcc(*addresses: Address | str) -> Self

Set the hidden recipients, replacing any set; no recipient sees them.

get_bcc

get_bcc() -> list[Address]

Return the hidden recipients.

priority

priority(priority: int) -> Self

Set X-Priority, from 1 (highest) to 5 (lowest); a value outside is brought inside.

get_priority

get_priority() -> int

Return the priority X-Priority starts with, normal (3) when it starts with none.

text

text(body: Body | None, charset: str = 'utf-8') -> Self

Set the text body, in charset; None takes it away.

Raises:

  • TypeError –

    body is not a string, bytes, a binary file or None.

get_text_body

get_text_body() -> Body | None

Return the text body as given, None unless set.

get_text_charset

get_text_charset() -> str | None

Return the charset of the text body, None unless set.

html

html(body: Body | None, charset: str = 'utf-8') -> Self

Set the HTML body, in charset; None takes it away.

Raises:

  • TypeError –

    body is not a string, bytes, a binary file or None.

get_html_body

get_html_body() -> Body | None

Return the HTML body as given, None unless set.

get_html_charset

get_html_charset() -> str | None

Return the charset of the HTML body, None unless set.

attach

attach(body: Body, name: str | None = None, content_type: str | None = None) -> Self

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

embed(body: Body, name: str | None = None, content_type: str | None = None) -> Self

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.

add_part

add_part(part: DataPart) -> Self

Attach part, after the attachments already there.

get_attachments

get_attachments() -> list[DataPart]

Return the attachments, in order; changing the list leaves the email as it is.

get_body

get_body() -> AbstractPart

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

ensure_validity() -> None

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

Group(name: str, addresses: Iterable[Address | str] = ())

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 –

    name is empty once cleaned: a group is written by its name.

  • RfcComplianceError –

    name holds a lone surrogate — what a byte that did not decode leaves in a str — or a member is not a valid email address.

get_name

get_name() -> str

Return the display name.

get_addresses

get_addresses() -> list[Address]

Return the members, in order; changing the list leaves the group as it is.

AbstractHeader

AbstractHeader(name: str)

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:

get_body abstractmethod

get_body() -> object

Return the body; each class says what type it is.

set_body abstractmethod

set_body(body: object) -> None

Replace the body, once checked to be of the type this header holds.

Raises:

set_charset

set_charset(charset: str) -> None

Set the charset the body is meant to be encoded in.

get_charset

get_charset() -> str

Return the charset, utf-8 unless set.

set_language

set_language(language: str) -> None

Set the language of the body, an RFC 5646 tag such as en-us.

get_language

get_language() -> str | None

Return the language, None unless set.

get_name

get_name() -> str

Return the name, as given.

set_max_line_length

set_max_line_length(line_length: int) -> None

Set the line length the header is meant to be folded at.

get_max_line_length

get_max_line_length() -> int

Return the line length, 76 unless set.

to_string

to_string() -> str

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

get_body_as_string() -> str

Return the body as the engine writes it, joined back onto one line, whatever the name.

Raises:

to_field

to_field() -> str | None

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:

DateHeader

DateHeader(name: str, date_time: datetime)

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:

set_body

set_body(body: object) -> None

Replace the date.

Raises:

get_body

get_body() -> datetime

Return the date.

get_date_time

get_date_time() -> datetime

Return the date.

set_date_time

set_date_time(date_time: datetime) -> None

Replace the date.

FoldedHeader

FoldedHeader(field: str)

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

set_body(body: object) -> None

Replace the body; the type depends on the header.

Raises:

get_body

get_body() -> object

Return the body; the type depends on the header.

set_charset

set_charset(charset: str) -> None

Set the charset the body is meant to be encoded in.

get_charset

get_charset() -> str

Return the charset, utf-8 unless set.

set_language

set_language(language: str) -> None

Set the language of the body, an RFC 5646 tag such as en-us.

get_language

get_language() -> str | None

Return the language, None unless set.

get_name

get_name() -> str

Return the name, as given.

set_max_line_length

set_max_line_length(line_length: int) -> None

Set the line length the header is meant to be folded at.

get_max_line_length

get_max_line_length() -> int

Return the line length, 76 unless set.

to_string

to_string() -> str

Return the whole field as written in a message, folded, without the final CRLF.

get_body_as_string

get_body_as_string() -> str

Return the body as written in a message, encoded but on one line.

Headers

Headers(*headers: HeaderInterface)

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_max_line_length(line_length: int) -> None

Set the line length on every header, and on every header added later.

get_max_line_length

get_max_line_length() -> int

Return the line length, 76 unless set.

add_mailbox_list_header

add_mailbox_list_header(name: str, addresses: Iterable[Address | Group | str]) -> Self

Add a list of addresses and groups; a string is read as an address.

add_mailbox_header

add_mailbox_header(name: str, address: Address | str) -> Self

Add one address; a string may be Name <address>.

add_id_header

add_id_header(name: str, ids: str | Iterable[str]) -> Self

Add one identifier or several.

add_path_header

add_path_header(name: str, path: Address | str) -> Self

Add a path; a string is the bare address.

add_date_header

add_date_header(name: str, date_time: datetime) -> Self

Add a date.

add_text_header

add_text_header(name: str, value: str) -> Self

Add free text.

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_header(name: str, argument: object, *more: object) -> Self

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:

has

has(name: str) -> bool

Tell whether a header of that name is there, whatever its case.

add

add(header: HeaderInterface) -> Self

Add header after the others, with this collection's line length.

Raises:

  • LogicError –

    header is not of the class its name needs, or it must be unique and one of its name is already there.

get

get(name: str) -> HeaderInterface | None

Return the first header of that name, whatever its case, None if there is none.

all

all(name: str | None = None) -> Iterator[HeaderInterface]

Yield every header in order, or every header of one name, whatever its case.

get_names

get_names() -> list[str]

Return the names, lowercased, in the order they were first added.

remove

remove(name: str) -> None

Remove every header of that name, whatever its case.

is_unique_header staticmethod

is_unique_header(name: str) -> bool

Tell whether a message carries a header of that name at most once.

check_header_class staticmethod

check_header_class(header: HeaderInterface) -> None

Check that header is of the class its name needs, if the class map names one.

Raises:

to_string

to_string() -> str

Return every header with a body, each field ending in CRLF.

to_array

to_array() -> list[str]

Return every header with a body as its folded field; one without a body is skipped.

get_header_body

get_header_body(name: str) -> object

Return the body of the first header of that name, None if there is none.

set_header_body

set_header_body(kind: HeaderKind, name: str, body: object) -> None

Replace the body of the first header of that name, or add one of kind.

Raises:

get_header_parameter

get_header_parameter(name: str, parameter: str) -> str | None

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_header_parameter(name: str, parameter: str, value: str | None) -> None

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

IdentificationHeader(name: str, ids: str | Iterable[str])

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:

set_body

set_body(body: object) -> None

Replace the identifiers with body, one or a sequence of them.

Raises:

get_body

get_body() -> list[str]

Return the identifiers.

set_id

set_id(ids: str | Iterable[str]) -> None

Replace the identifiers with one, or with several.

Raises:

get_id

get_id() -> str | None

Return the first identifier, None when there is none.

set_ids

set_ids(ids: Iterable[str]) -> None

Replace the identifiers.

Raises:

get_ids

get_ids() -> list[str]

Return the identifiers, as given.

MailboxHeader

MailboxHeader(name: str, address: Address)

Bases: AbstractHeader

A header whose body is one address, written name <address> or the address alone.

Keep name and address.

Raises:

set_body

set_body(body: object) -> None

Replace the address.

Raises:

get_body

get_body() -> Address

Return the address.

set_address

set_address(address: Address) -> None

Replace the address.

get_address

get_address() -> Address

Return the address.

MailboxListHeader

MailboxListHeader(name: str, addresses: Iterable[Address | Group])

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:

create_address_list staticmethod

create_address_list(addresses: Iterable[Address | Group | str]) -> list[Address | Group]

Turn every entry that is not already an address or a group into an address.

Raises:

set_body

set_body(body: object) -> None

Replace the address list.

Raises:

get_body

get_body() -> list[Address]

Return every mailbox, group members included.

set_addresses

set_addresses(addresses: Iterable[Address | Group]) -> None

Replace the address list.

add_addresses

add_addresses(addresses: Iterable[Address | Group]) -> None

Append to the address list, in order.

add_address

add_address(address: Address | Group) -> None

Append one address or group to the address list.

get_addresses

get_addresses() -> list[Address]

Return every mailbox, group members included, in order.

get_address_list

get_address_list() -> list[Address | Group]

Return the address list as given: addresses and groups.

get_address_strings

get_address_strings() -> list[str]

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

ParameterizedHeader(name: str, value: str, parameters: Mapping[str, str | None] | None = None)

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 –

    name is not a header name, or a parameter name is not a token or is longer than 40 characters.

set_parameter

set_parameter(parameter: str, value: str | None) -> None

Set one parameter, replacing it if it is there; None keeps it unwritten.

Raises:

get_parameter

get_parameter(parameter: str) -> str

Return a parameter's value, empty when it is not set or set to None.

set_parameters

set_parameters(parameters: Mapping[str, str | None]) -> None

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.

get_parameters

get_parameters() -> dict[str, str | None]

Return the parameters, in order.

PathHeader

PathHeader(name: str, address: Address)

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:

set_body

set_body(body: object) -> None

Replace the address.

Raises:

get_body

get_body() -> Address

Return the address.

set_address

set_address(address: Address) -> None

Replace the address.

get_address

get_address() -> Address

Return the address.

UnstructuredHeader

UnstructuredHeader(name: str, value: str)

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:

set_body

set_body(body: object) -> None

Replace the text.

Raises:

get_body

get_body() -> str

Return the text, as given.

get_value

get_value() -> str

Return the text, as given: not encoded.

set_value

set_value(value: str) -> None

Replace the text.

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.

convert

convert(html: str, charset: str) -> str

Return the text html reads as.

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

convert(html: str, charset: str) -> str

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

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

is_guesser_supported() -> bool

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

guess_mime_type(path: str) -> str | None

Name the type libmagic reads in the file at path.

Returns:

  • str | None –

    The MIME type, or None when libmagic answers nothing.

Raises:

  • InvalidArgumentError –

    When path does 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_body

set_body(body: AbstractPart | None) -> Self

Replace the body part.

get_body

get_body() -> AbstractPart | None

Return the body part, None unless set.

set_headers

set_headers(headers: Headers) -> Self

Replace the headers with headers itself, not a copy.

get_headers

get_headers() -> Headers

Return the headers the caller set, which the caller may change.

get_prepared_headers

get_prepared_headers() -> 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

to_string() -> str

Render the message: its prepared headers, then its body.

Raises:

to_iterable

to_iterable() -> Generator[bytes]

Render the message in the pieces the engine writes, as a mail server receives them.

Raises:

ensure_validity

ensure_validity() -> None

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

generate_message_id() -> str

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

to_email(message: Message) -> Email

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

is_guesser_supported() -> bool

Tell whether this guesser can run on this host.

guess_mime_type

guess_mime_type(path: str) -> str | None

Name the MIME type of the file at path.

Returns:

  • str | None –

    The MIME type, or None when this guesser cannot tell.

Raises:

MimeTypes

MimeTypes(extra_map: Mapping[str, Sequence[str]] | None = None)

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

get_default() -> MimeTypes

Return the shared table, built on first use unless :meth:set_default gave one.

set_default classmethod

set_default(default: MimeTypes) -> None

Make default the table :meth:get_default returns from now on.

register_guesser

register_guesser(guesser: MimeTypeGuesserInterface) -> None

Ask guesser before every guesser registered so far, the libmagic one included.

get_extensions

get_extensions(mime_type: str) -> list[str]

Return the extensions of files of mime_type, the preferred one first.

get_mime_types

get_mime_types(extension: str) -> list[str]

Return the MIME types of files ending in extension, the preferred one first.

is_guesser_supported

is_guesser_supported() -> bool

Answer True: the table answers whenever no registered guesser can.

guess_mime_type

guess_mime_type(path: str) -> str | None

Name the type of the file at path: its guessers' answer, else its extension's.

Returns:

  • str | None –

    The MIME type, or None when no guesser answers and the table does not know the

  • str | None –

    file's extension.

Raises:

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

get_extensions(mime_type: str) -> list[str]

Return the extensions of files of mime_type, the preferred one first.

Returns:

  • list[str] –

    The extensions, or an empty list for a type the table does not know.

get_mime_types

get_mime_types(extension: str) -> list[str]

Return the MIME types of files ending in extension, the preferred one first.

Returns:

  • list[str] –

    The MIME types, or an empty list for an extension the table does not know.

AbstractMultipartPart

AbstractMultipartPart(*parts: AbstractPart)

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.

get_parts

get_parts() -> Sequence[AbstractPart]

Return the parts, in order.

get_media_type

get_media_type() -> str

Return multipart.

get_prepared_headers

get_prepared_headers() -> Headers

Return the headers with the boundary set on Content-Type.

as_debug_string

as_debug_string() -> str

Describe the part and, indented below it, each of its parts.

AbstractPart

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.

get_headers

get_headers() -> Headers

Return the part's own headers, which the caller may add to.

set_content_type_parameter

set_content_type_parameter(name: str, value: str) -> Self

Set a parameter of Content-Type, such as method for text/calendar.

Raises:

get_prepared_headers

get_prepared_headers() -> 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

to_string() -> str

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:

to_iterable

to_iterable() -> Iterator[bytes]

Render the part in the pieces the engine writes, as a mail server receives them.

Raises:

body_to_string

body_to_string() -> str

Render the encoded body alone, as :meth:to_string writes it.

body_to_iterable

body_to_iterable() -> Iterator[bytes]

Render the encoded body alone, as :meth:to_iterable writes it.

as_debug_string

as_debug_string() -> str

Describe the part in one line: its media type.

get_media_type abstractmethod

get_media_type() -> str

Return the media type, the part of Content-Type before the slash.

get_media_subtype abstractmethod

get_media_subtype() -> str

Return the media subtype, the part of Content-Type after the slash.

AlternativePart

AlternativePart(*parts: AbstractPart)

Bases: AbstractMultipartPart

The same content in several forms, the one a reader prefers last: text, then HTML.

get_media_subtype

get_media_subtype() -> str

Return alternative.

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:

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 –

    path is a directory or a file this process may not read, or encoding is not one the part knows.

as_inline

as_inline() -> Self

Show the part inside the body, not as an attachment.

set_content_id

set_content_id(content_id: str) -> Self

Set the content id, left@right without angle brackets.

Raises:

get_content_id

get_content_id() -> str

Return the content id, made up now if none was set or made up before.

has_content_id

has_content_id() -> bool

Tell whether a content id was set or made up.

get_media_type

get_media_type() -> str

Return the media type of the content type given.

get_prepared_headers

get_prepared_headers() -> Headers

Return the text part's headers with the content id and the filename added.

as_debug_string

as_debug_string() -> str

Describe the part: the text part's description and the filename.

get_filename

get_filename() -> str | None

Return the filename, None unless given.

get_content_type

get_content_type() -> str

Return type/subtype.

DigestPart

DigestPart(*parts: MessagePart)

Bases: AbstractMultipartPart

Messages gathered into one, as a mailing list digest is; every part is a message.

Keep the messages, in order.

get_media_subtype

get_media_subtype() -> str

Return digest.

File

File(path: str | PathLike[str], filename: str | None = None)

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.

get_path

get_path() -> str

Return the path, as given.

get_content_type

get_content_type() -> str

Return the type of a file with this extension, application/octet-stream if none.

The extension decides, not the content: the file is not read.

get_size

get_size() -> int

Return the size of the file in bytes, read from the file system.

Raises:

  • OSError –

    The file cannot be looked at.

get_filename

get_filename() -> str

Return the name given, else the base name of the path.

FormDataPart

FormDataPart(fields: FormFields = ())

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_media_subtype

get_media_subtype() -> str

Return form-data.

get_parts

get_parts() -> list[TextPart]

Return a part per field, named after it, with the form-data disposition.

to_string

to_string() -> str

Render the Content-Type header, a blank line and the body.

Raises:

to_iterable

to_iterable() -> Iterator[bytes]

Render the Content-Type header, a blank line and the body, in pieces.

Raises:

body_to_string

body_to_string() -> str

Render the body; bytes that are not UTF-8 survive as surrogates.

body_to_iterable

body_to_iterable() -> Iterator[bytes]

Render the body, field by field: what an HTTP client sends.

Raises:

MessagePart

MessagePart(message: _RenderableMessage)

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.

get_message

get_message() -> _RenderableMessage

Return the message carried, as it was given.

get_body

get_body() -> str

Return the message, rendered.

MixedPart

MixedPart(*parts: AbstractPart)

Bases: AbstractMultipartPart

Independent parts shown one after the other: the body first, then the attachments.

get_media_subtype

get_media_subtype() -> str

Return mixed.

RelatedPart

RelatedPart(main_part: AbstractPart, part: AbstractPart, *parts: AbstractPart)

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.

get_media_subtype

get_media_subtype() -> str

Return related.

SMimePart

SMimePart(body: str | bytes, media_type: str, media_subtype: str, parameters: Mapping[str, str])

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, boundary for a multipart.

get_prepared_headers

get_prepared_headers() -> 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 –

    body is none of the types a body may be.

  • InvalidArgumentError –

    body is a :class:File naming a directory or a file this process may not read, or encoding is not one the part knows.

get_media_type

get_media_type() -> str

Return text.

get_media_subtype

get_media_subtype() -> str

Return the subtype given, plain by default.

set_disposition

set_disposition(disposition: str) -> Self

Set how the part is shown: attachment, inline or form-data.

get_disposition

get_disposition() -> str | None

Return the disposition, None unless set.

set_name

set_name(name: str) -> Self

Set the name of the part: a file's name, or a form field's.

get_name

get_name() -> str | None

Return the name, None unless set.

get_body

get_body() -> str | bytes

Return the body before transfer encoding: a string as given, bytes otherwise.

Raises:

get_prepared_headers

get_prepared_headers() -> 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

as_debug_string() -> str

Describe the part: its media type, charset and disposition.

RawMessage

RawMessage(message: str | bytes | BinaryIO | Iterable[bytes])

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

to_string() -> str

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:

to_iterable

to_iterable() -> Generator[bytes]

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:

ensure_validity

ensure_validity() -> None

Check the message can be sent; a raw message always can.

Raises:

  • LogicError –

    In a subclass, the message cannot be sent as it is.