Skip to content

xtr_mailer

Email sent through SMTP, sendmail or a provider's API, picked by a DSN.

A :class:Mailer hands each email to a transport built from a DSN (smtp://localhost:25, sendmail://default, failover(smtp://a smtp://b)) and sends it in-process, or queues it on a message bus for a worker to send. Listeners on the way override the envelope and headers, and sign the email with DKIM or S/MIME.

An :class:Envelope is who an email is delivered for and to, apart from its headers; :class:SentMessage is what a transport sent. A :class:RemoteTemplateEmail is rendered by the mail provider from a :class:RemoteTemplate it hosts. :class:Transport builds the transport a DSN string describes.

Envelope

Envelope(sender: Address, recipients: Iterable[Address])

Who an email is delivered for and to: the SMTP MAIL FROM and RCPT TO.

The envelope is what a server delivers by, whatever the headers show: a Bcc recipient is in the envelope and in no header, and a bounce goes to the envelope's sender. The recipients are bare addresses, their names dropped — a server has no use for them.

Keep sender and recipients, once checked.

Raises:

  • InvalidArgumentError –

    The sender is not an address or has a non-ASCII local part, or there is no recipient, or a recipient is not an address.

create staticmethod

create(message: RawMessage) -> Envelope

Return the envelope message's own headers give, read when it is asked for.

The sender is the Sender header, else the Return-Path, else the first author; the recipients are every address of To, Cc and Bcc, group members included. Each is read from the headers as they are when asked for, until it is set.

Raises:

  • LogicError –

    message is raw bytes, which have no headers to read.

set_sender

set_sender(sender: Address) -> None

Replace the sender, who a bounce goes back to.

Its local part must be ASCII: a bounce must reach it through any server, whether or not that server speaks SMTPUTF8.

Raises:

get_sender

get_sender() -> Address

Return the sender, with its name; MAIL FROM takes its bare address.

set_recipients

set_recipients(recipients: Iterable[Address]) -> None

Replace the recipients with their bare addresses, names dropped.

Raises:

get_recipients

get_recipients() -> list[Address]

Return the recipients, in order; changing the list leaves the envelope as it is.

any_address_has_unicode_localpart

any_address_has_unicode_localpart() -> bool

Tell whether the sender or a recipient has a non-ASCII local part.

Such an address can only be sent through a server speaking SMTPUTF8 (RFC 6531); a non-ASCII domain alone is written in punycode and needs nothing special.

HttpTransportError

HttpTransportError(message: str, response: HttpResponseInterface, code: int = 0)

Bases: TransportError

A provider's API answered an email with a refusal.

It carries the response, so a caller can read what the provider said beyond the message.

Attributes:

Record why the provider refused the email and what it answered.

Parameters:

  • message (str) –

    Why the send failed, in the provider's words where it gave any.

  • response (HttpResponseInterface) –

    What the provider answered with.

  • code (int, default: 0 ) –

    The status the provider answered with, 0 when not given.

IncompleteDsnError

Bases: InvalidArgumentError

A DSN parses, but lacks a part its transport cannot work without — a user, a password.

The message names the missing part only, never the DSN, which carries credentials.

InvalidArgumentError

Bases: MailerError, ValueError

A value handed to this library cannot be used: a malformed DSN, an envelope with no sender.

Also a :class:ValueError, so code that already guards against a bad value catches it without knowing this library exists.

LogicError

Bases: MailerError, RuntimeError

This library was used in a way that cannot work, whatever the email carries.

A DSN scheme no installed factory serves, a transport handed an email it was never built for: each is a mistake in the code or the configuration, so retrying it changes nothing.

MailerError

Bases: Exception

Something an email could not be sent through — catch this to catch them all.

MailerRuntimeError

Bases: MailerError, RuntimeError

Something an email depends on failed while it was sent — a server, a process.

The input was fine and the code is fine; the world did not cooperate. Raising one out of a message handler is what makes a message bus retry the send.

TransportError

TransportError(message: str, code: int = 0)

Bases: MailerRuntimeError

A server could not be reached, or refused an email.

It is the one error a round-robin or failover transport takes as a sign that a transport is down: anything else is a mistake that another transport would make too.

Attributes:

  • code (int) –

    The reply code the server refused with — an SMTP reply code, an HTTP status — or 0 when there was none. SMTP transports tell a refusal from a dropped connection by it.

  • debug (str) –

    The protocol transcript up to the failure, so a caller can see what was said. Authentication exchanges are kept out of it: it never carries credentials.

Record why the email could not be handed over.

Parameters:

  • message (str) –

    Why the transport failed.

  • code (int, default: 0 ) –

    The reply code the server refused with, 0 when there was none.

append_debug

append_debug(debug: str) -> None

Add debug to the transcript.

The error is raised from deep inside a transport, which only knows its own part of the exchange; each layer it passes through appends what it saw.

UnexpectedResponseError

UnexpectedResponseError(message: str, code: int = 0)

Bases: TransportError

An SMTP server replied to a command with a code the command does not accept.

Its :attr:code is the reply code the server sent: an SMTP transport resets the session after a refusal, but not after 421, the server closing the connection, and authentication tries the next mechanism after one.

UnsupportedSchemeError

UnsupportedSchemeError(scheme: str, name: str | None = None, supported: Sequence[str] = ())

Bases: LogicError

No factory serves a DSN's scheme.

The common cause is a provider library that is not installed, so a scheme a first-party provider library serves is answered with the command that installs it — this package's extra named after the provider, quoted so a shell does not read its brackets. Any other scheme is answered with the schemes that are supported, when the caller knows them. The message names the scheme only: never the DSN, which carries credentials — and shows it escaped and cut short, as it is whatever the application's configuration says.

Attributes:

  • scheme (str) –

    The scheme no factory serves.

  • name (str | None) –

    The mailer transport that was being built, or None.

  • supported (tuple[str, ...]) –

    The schemes that are supported there.

Explain why scheme has no transport.

Takes the scheme rather than the DSN, so nothing that carries credentials ever reaches an error.

Parameters:

  • scheme (str) –

    The scheme of the DSN no factory serves.

  • name (str | None, default: None ) –

    The transport being built, named in the message with supported.

  • supported (Sequence[str], default: () ) –

    The schemes that are supported there.

Mailer

Mailer(transport: TransportInterface, message_bus: MessageBusInterface | None = None, event_dispatcher: EventDispatcherInterface | None = None)

Bases: MailerInterface

Sends each email through the transport, or — given a message bus — queues it there.

Mailer(transport) sends at once. Mailer(transport, bus, dispatcher) dispatches a :class:~xtr_mailer.messenger.SendEmailMessage on the bus instead, for its handler to send through the same transport, possibly in another process. Before that, a :class:~xtr_mailer.event.MessageEvent with queued set goes to the dispatcher, on a copy of the email and of the envelope: a listener may reject the email, so nothing is queued, or add the stamps it is dispatched with — but what is queued is the email as given, since the listeners run again on it when the transport sends it.

When the bus handles the email in this process and the transport refuses it, the transport's error is raised, not the bus's report of the failed handlers.

The bus is only ever called, so the messenger package is needed only by an application that hands one over.

Send through transport, or queue on message_bus when given one.

Parameters:

  • transport (TransportInterface) –

    What sends the emails, now or when the bus hands them back.

  • message_bus (MessageBusInterface | None, default: None ) –

    Where emails are queued instead of sent now; None sends every email at once.

  • event_dispatcher (EventDispatcherInterface | None, default: None ) –

    Where a queued email is announced; None announces nothing and queues every email with no stamps. An email sent now is announced by the transport, on its own dispatcher.

send async

send(message: RawMessage, envelope: Envelope | None = None) -> None

Send message now, or queue it unless a listener rejects it.

Raises:

  • LogicError –

    message is raw bytes queued with no envelope while events are dispatched, or sent now with none.

  • TransportError –

    The transport could not send the email, now or from a handler of the bus in this process.

MailerInterface

Bases: Protocol

Sends an email now, or queues it on a message bus for a worker to send.

Code sending email depends on this rather than on a transport: whether the email leaves in this process or in a worker is the application's configuration, not the caller's.

send async

send(message: RawMessage, envelope: Envelope | None = None) -> None

Send or queue message with envelope, or the envelope its headers give.

Raises:

  • TransportError –

    The email was sent now, or by a handler of the bus in this process, and the server could not be reached or refused it.

RemoteTemplate

RemoteTemplate(reference: str, variables: Mapping[str, object] | None = None)

A template hosted by the mail provider: which one, and the variables it is rendered with.

The reference is whatever the provider names a template by — an id, a name, an alias. The variables are copied in and out: the template does not change once made.

Keep reference and a copy of variables.

get_reference

get_reference() -> str

Return the provider-side reference of the template.

get_variables

get_variables() -> dict[str, object]

Return a copy of the variables the provider renders the template with.

RemoteTemplateEmail

RemoteTemplateEmail(headers: Headers | None = None, body: AbstractPart | None = None, *, clock: ClockInterface | None = None)

Bases: Email

An email whose body the mail provider renders from one of its templates.

Only a transport able to hand the template over sends it; any other refuses it, rather than deliver the placeholder that stands for the body here. With no template set it is an ordinary email.

Start as an ordinary email, with no template.

template

template(template: str | None, variables: Mapping[str, object] | None = None) -> Self

Render the email from the provider's template with variables; None stops.

get_remote_template

get_remote_template() -> RemoteTemplate | None

Return the template, None unless set.

get_body

get_body() -> AbstractPart

Return a text part naming the template when one is set, else the email's body.

Raises:

  • LogicError –

    There is no template, no body set, no text, no HTML and no attachment.

  • InvalidArgumentError –

    The HTML body is bytes in a charset Python does not know.

SentMessage

SentMessage(message: RawMessage, envelope: Envelope, *, render_now: bool = True)

What a transport sent, and what it learned sending it.

A :class:~xtr_mime.Message is rendered once, here, from a copy given a Message-ID when it has none: the bytes a transport writes, a signature covers and a listener reads afterwards are the same bytes, and the caller's message is left as it was. Raw bytes are sent as they are.

The message id is the transport's: the Message-ID of a message, until the transport sets the id its server gave (an SMTP 250 Ok queued as ..., a provider's API id). A raw message has none until then.

A transport that never sends the bytes — one handing a provider's API the email's fields — leaves the message unrendered: it is rendered the first time it is read, if ever, so the send does not stop on a header the engine would refuse and the API accepts.

Check message can be sent and render it, now or when it is first read.

Parameters:

  • message (RawMessage) –

    What is sent.

  • envelope (Envelope) –

    Who it is sent for and to.

  • render_now (bool, default: True ) –

    Whether a message is rendered here; False renders it the first time it is read, raising there what rendering raises.

Raises:

  • LogicError –

    The message cannot be sent as it is: no recipient, no author, no body, or a draft.

  • MimeError –

    The message cannot be rendered — a header or a body the engine refuses — and is rendered now.

get_message

get_message() -> RawMessage

Return what is sent: the message rendered, or the raw message itself.

get_original_message

get_original_message() -> RawMessage

Return the message as the caller handed it over.

get_envelope

get_envelope() -> Envelope

Return the envelope the message was sent with.

set_message_id

set_message_id(message_id: str) -> None

Replace the message id with the one the transport's server gave.

get_message_id

get_message_id() -> str

Return the transport's message id, empty for a raw message until one is set.

For a message it starts as the Message-ID header of what was rendered, until the transport sets the one its server gave.

get_debug

get_debug() -> str

Return what the transport logged while sending, empty unless it logged anything.

append_debug

append_debug(debug: str) -> None

Append to what the transport logged.

to_string

to_string() -> str

Return what is sent, as text.

to_iterable

to_iterable() -> Generator[bytes]

Yield what is sent, as a mail server receives it.

Dsn

Dsn(scheme: str, host: str, user: str | None = None, password: str | None = None, port: int | None = None, options: Mapping[str, DsnOption | None] | None = None)

A parsed mailer DSN.

The scheme and the host keep the case they were written in: the errors naming a scheme show what the application configured, not a normalised copy of it. The user and the password are percent-decoded, so a password holding a reserved character is written escaped and read back whole; an empty one is None, as if it were not written.

Assemble a DSN from its parts, as :meth:from_string does once it has read them.

Parameters:

  • scheme (str) –

    What a factory dispatches on.

  • host (str) –

    The host, default standing for the provider's own.

  • user (str | None, default: None ) –

    The decoded user, or None.

  • password (str | None, default: None ) –

    The decoded password, or None.

  • port (int | None, default: None ) –

    The port, or None for the transport's own.

  • options (Mapping[str, DsnOption | None] | None, default: None ) –

    The query options; an option set to None reads as unset.

scheme property

scheme: str

What a factory dispatches on, as written.

host property

host: str

The host, default standing for the provider's own.

user property

user: str | None

The decoded user, or None when the DSN carries none.

password property

password: str | None

The decoded password, or None when the DSN carries none.

from_string classmethod

from_string(dsn: str) -> Dsn

Read dsn into its parts.

Parameters:

  • dsn (str) –

    The DSN as configured. It carries credentials: it is never kept, and no error raised here quotes it or chains an error that does. Whitespace around it is ignored, as an environment file often adds some.

Raises:

  • InvalidArgumentError –

    If dsn cannot be read as a URL, carries a control character inside it, carries no scheme, or carries no host.

get_port

get_port(default: int | None = None) -> int | None

Return the port, or default — the transport's own — when the DSN names none.

get_option

get_option(key: str) -> DsnOption | None
get_option(key: str, default: T) -> DsnOption | T
get_option(key: str, default: object = None) -> object

Return the option key, or default when the DSN does not set it.

get_boolean_option

get_boolean_option(key: str, default: bool = False) -> bool

Return the option key read as a boolean, or default when it is not set.

1, true, on and yes are true; 0, false, off, no and an empty value are false, in any case.

Raises:

  • InvalidArgumentError –

    If the value is none of those. A typo such as verify_peer=fasle would otherwise quietly read as false. The value is quoted only when it is one plain word.

Transport

Transport(factories: Iterable[TransportFactoryInterface] = (), discovery: TransportFactoryDiscovery | None = None, *, rate_limiter_factories: Mapping[str, RateLimiterFactoryInterface] | None = None, logger: LoggerInterface | None = None)

Turns DSN strings into transports, through the factories serving their schemes.

One DSN builds one transport; the keywords failover(...) and roundrobin(...) group DSNs separated by spaces into a :class:FailoverTransport or a :class:RoundRobinTransport, nesting as deep as needed, each group optionally followed by the seconds a failed member rests for::

transport = Transport.from_dsn(
    "roundrobin(smtp://a failover(smtp://b smtp://c))?retry_period=15",
    event_dispatcher=dispatcher,
)

A scheme is looked up in the factories given first, in order, then among those the discovery finds installed. The DSN strings carry credentials: none is kept, and no error raised here quotes one.

A group logs each member that fails, through the logger the builder is given; it is never capped by a rate limiter, which caps a single transport only.

Build through factories, then through the ones discovery finds.

Parameters:

  • factories (Iterable[TransportFactoryInterface], default: () ) –

    Factories tried first, in order — an application's own, or one needing more than discovery hands it.

  • discovery (TransportFactoryDiscovery | None, default: None ) –

    Where to look for a scheme no factory given serves; None uses the given factories only.

  • rate_limiter_factories (Mapping[str, RateLimiterFactoryInterface] | None, default: None ) –

    The limiter each named transport of :meth:from_strings is capped by, keyed by its name; a name not listed is not capped. A limiter given for a transport that takes none — a failover(...) or roundrobin(...) group — is refused when it is built.

  • logger (LoggerInterface | None, default: None ) –

    Where each group built logs a member that fails; None logs nothing. The members log where their factory was told to.

from_dsn classmethod

from_dsn(dsn: str, event_dispatcher: EventDispatcherInterface | None = None, http_client: HttpClientInterface | None = None, logger: LoggerInterface | None = None) -> TransportInterface

Build the transport dsn describes through the installed factories.

Parameters:

  • dsn (str) –

    One DSN, or a keyword group of them.

  • event_dispatcher (EventDispatcherInterface | None, default: None ) –

    Where the transports built announce emails.

  • http_client (HttpClientInterface | None, default: None ) –

    What transports reaching their provider over HTTP use; a scheme needing one is refused without it.

  • logger (LoggerInterface | None, default: None ) –

    Where the transports built log, groups included.

Raises:

from_dsns classmethod

from_dsns(dsns: Mapping[str, str], event_dispatcher: EventDispatcherInterface | None = None, http_client: HttpClientInterface | None = None, logger: LoggerInterface | None = None) -> Transports

Build a transport per named DSN through the installed factories, as :meth:from_dsn.

Raises:

from_strings

from_strings(dsns: Mapping[str, str]) -> Transports

Build a transport per named DSN, picked per email by name, the first by default.

Each is capped by the rate limiter given for its name, if any.

Raises:

from_string

from_string(dsn: str, rate_limiter_factory: RateLimiterFactoryInterface | None = None) -> TransportInterface

Build the transport dsn describes — one, or a keyword group of them.

Parameters:

  • dsn (str) –

    One DSN, or a keyword group of them.

  • rate_limiter_factory (RateLimiterFactoryInterface | None, default: None ) –

    Caps the transport built, which must take a rate limiter: a failover(...) or roundrobin(...) group takes none.

Raises:

from_dsn_object

from_dsn_object(dsn: Dsn) -> TransportInterface

Build the transport a parsed dsn describes.

Raises:

  • UnsupportedSchemeError –

    No factory serves the scheme. It names the provider library to install when the scheme is a known one.