email#

Transactional React Email service wrapper.

Email module wrapping litestar-email with template-backed AppEmailService.

class app.lib.email.AppEmailService(mailer: EmailService)[source]#

Bases: object

Template-rendering transactional email adapter over litestar-email EmailService.

Initialize the email service with a request- or task-scoped EmailService.

__init__(mailer: EmailService) → None[source]#

Initialize the email service with a request- or task-scoped EmailService.

property app_name: str#

Configured application display name.

property base_url: str#

Configured application base URL.

async send_email(to_email: str | list[str], subject: str, html_content: str, text_content: str | None = None, from_email: str | None = None, reply_to: str | None = None, *, template_name: str | None = None) → bool[source]#

Send an HTML + plain-text multipart email and log structured delivery failures.

Returns:

True if at least one message was accepted by the email backend.

Raises:
  • EmailRateLimitError – If the email backend rejects the request due to rate limiting.

  • EmailAuthenticationError – If backend authentication fails.

  • EmailConnectionError – If the backend connection fails.

  • EmailDeliveryError – If the backend reports a delivery failure.

async send_verification_email(user: UserProtocol, verification_token: str) → bool[source]#

Send an account email verification message.

Returns:

True if the message was sent.

async send_welcome_email(user: UserProtocol) → bool[source]#

Send a welcome message to a newly verified user.

Returns:

True if the message was sent.

async send_password_reset_email(user: UserProtocol, reset_token: str, expires_in_minutes: int = 60) → bool[source]#

Send a password reset message.

Returns:

True if the message was sent.

async send_password_reset_confirmation_email(user: UserProtocol) → bool[source]#

Send a password reset confirmation message.

Returns:

True if the message was sent.

async send_team_invitation_email(invitee_email: str, inviter_name: str, team_name: str, invitation_url: str) → bool[source]#

Send a team invitation message.

Returns:

True if the message was sent.

class app.lib.email.EmailConfig(backend: str | SMTPConfig | ResendConfig | SendGridConfig | MailgunConfig | SESConfig = 'console', from_email: str = 'noreply@localhost', from_name: str = '', fail_silently: bool = False, email_service_dependency_key: str = 'mailer', email_service_state_key: str = 'mailer')[source]#

Bases: object

Configuration for the EmailPlugin.

This configuration class defines the settings for sending email within a Litestar application.

Example

Basic configuration with console backend:

config = EmailConfig(
    backend="console",
    from_email="noreply@example.com",
    from_name="My App",
)

Configuration with SMTP backend:

config = EmailConfig(
    backend=SMTPConfig(
        host="smtp.example.com",
        port=587,
        use_tls=True,
    ),
    from_email="noreply@example.com",
)

Configuration with Resend API backend:

config = EmailConfig(
    backend=ResendConfig(api_key="re_123abc..."),
    from_email="noreply@example.com",
)
property signature_namespace: dict[str, Any]#

Return the plugin’s signature namespace.

Returns:

A string keyed dict of names to be added to the namespace for signature forward reference resolution.

property dependencies: dict[str, Any]#

Return dependency providers for the plugin.

Returns:

A mapping of dependency keys to providers for Litestar’s DI system.

get_service(state: State | None = None) → EmailService[source]#

Return an EmailService for this configuration.

Parameters:

state – Optional application state to fetch a cached service instance or config.

Returns:

An EmailService instance.

get_backend(fail_silently: bool | None = None) → BaseEmailBackend[source]#

Return a backend instance configured for this EmailConfig.

Parameters:

fail_silently – Optional override for fail_silently behavior.

Returns:

A configured backend instance.

__init__(backend: str | SMTPConfig | ResendConfig | SendGridConfig | MailgunConfig | SESConfig = 'console', from_email: str = 'noreply@localhost', from_name: str = '', fail_silently: bool = False, email_service_dependency_key: str = 'mailer', email_service_state_key: str = 'mailer') → None#
provide_service() → AsyncServiceProvider[source]#

Provide an EmailService instance.

Returns a context manager that yields an EmailService with managed connection lifecycle.

Example:

async with config.provide_service() as mailer:
    await mailer.send_message(message)
Returns:

An AsyncServiceProvider that yields an EmailService instance.

class app.lib.email.EmailMessage(subject: str, body: str, from_email: str | None = None, to: list[str] = <factory>, cc: list[str] = <factory>, bcc: list[str] = <factory>, reply_to: list[str] = <factory>, headers: dict[str, str]=<factory>, attachments: list[tuple[str, bytes, str]]=<factory>, alternatives: list[tuple[str, str]]=<factory>)[source]#

Bases: object

A container for email message data.

This dataclass holds all the information needed to send an email, including recipients, content, and optional attachments.

attach(filename: str, content: bytes, mimetype: str) → None[source]#

Add an attachment to the email.

Parameters:
  • filename – The name of the attachment file.

  • content – The binary content of the attachment.

  • mimetype – The MIME type of the attachment (e.g., “application/pdf”).

attach_alternative(content: str, mimetype: str) → None[source]#

Add an alternative content representation.

Typically used to add an HTML version of the email alongside the plain text body.

Parameters:
  • content – The alternative content (e.g., HTML).

  • mimetype – The MIME type (e.g., “text/html”).

recipients() → list[str][source]#

Return all recipients of the email.

Returns:

A combined list of all to, cc, and bcc recipients.

__init__(subject: str, body: str, from_email: str | None = None, to: list[str] = <factory>, cc: list[str] = <factory>, bcc: list[str] = <factory>, reply_to: list[str] = <factory>, headers: dict[str, str]=<factory>, attachments: list[tuple[str, bytes, str]]=<factory>, alternatives: list[tuple[str, str]]=<factory>) → None#
class app.lib.email.EmailMultiAlternatives(subject: str, body: str, from_email: str | None = None, to: list[str] = <factory>, cc: list[str] = <factory>, bcc: list[str] = <factory>, reply_to: list[str] = <factory>, headers: dict[str, str]=<factory>, attachments: list[tuple[str, bytes, str]]=<factory>, alternatives: list[tuple[str, str]]=<factory>, html_body: str | None = None)[source]#

Bases: EmailMessage

An email message with HTML content support.

This convenience class extends EmailMessage to automatically attach an HTML body as an alternative representation.

__post_init__() → None[source]#

Automatically attach html_body as an alternative if provided.

__init__(subject: str, body: str, from_email: str | None = None, to: list[str] = <factory>, cc: list[str] = <factory>, bcc: list[str] = <factory>, reply_to: list[str] = <factory>, headers: dict[str, str]=<factory>, attachments: list[tuple[str, bytes, str]]=<factory>, alternatives: list[tuple[str, str]]=<factory>, html_body: str | None = None) → None#
class app.lib.email.EmailPlugin(config: EmailConfig | None = None)[source]#

Bases: InitPluginProtocol

Litestar plugin for email functionality.

This plugin provides email sending capabilities for Litestar applications. It supports multiple backend providers (SMTP, SendGrid, Resend, etc.) through a pluggable backend system.

Example

Basic plugin configuration:

from litestar import Litestar
from litestar_email import EmailConfig, EmailPlugin, SMTPConfig

email_config = EmailConfig(
    backend=SMTPConfig(host="localhost", port=1025),
    from_email="noreply@example.com",
)
app = Litestar(plugins=[EmailPlugin(config=email_config)])

Dependency injection in route handlers:

from litestar import get
from litestar_email import EmailMessage, EmailService

@get("/welcome/{email:str}")
async def send_welcome(email: str, mailer: EmailService) -> dict[str, str]:
    await mailer.send_message(
        EmailMessage(subject="Welcome!", body="Thanks for signing up.", to=[email]),
    )
    return {"status": "sent"}

Standalone usage with context manager:

from litestar_email import EmailConfig, EmailMessage, SMTPConfig

config = EmailConfig(
    backend=SMTPConfig(host="localhost", port=1025),
    from_email="noreply@example.com",
)

async with config.provide_service() as mailer:
    await mailer.send_message(
        EmailMessage(subject="Hello", body="World", to=["user@example.com"]),
    )

Using with event listeners:

Note: Event listeners in Litestar execute outside request context and
cannot receive DI-injected dependencies. Pass the mailer explicitly.

from litestar import get
from litestar.events import listener
from litestar_email import EmailMessage, EmailService

@get("/register/{email:str}")
async def register(email: str, mailer: EmailService) -> dict[str, str]:
    # Pass the DI-injected mailer to the event
    request.app.emit("user.registered", email, mailer=mailer)
    return {"status": "queued"}

@listener("user.registered")
async def on_user_registered(email: str, mailer: EmailService) -> None:
    # mailer is passed explicitly from emit(), not injected via DI
    await mailer.send_message(
        EmailMessage(subject="Welcome!", body="Thanks!", to=[email]),
    )

Initialize the email plugin.

Parameters:

config – Optional email configuration. If not provided, defaults will be used.

__init__(config: EmailConfig | None = None) → None[source]#

Initialize the email plugin.

Parameters:

config – Optional email configuration. If not provided, defaults will be used.

property config: EmailConfig#

Return the plugin configuration.

Returns:

The email configuration instance.

get_service(state: State | None = None) → EmailService[source]#

Return an EmailService for this plugin.

Parameters:

state – Optional application state to fetch a cached service instance or config.

Returns:

An EmailService instance.

get_backend(fail_silently: bool | None = None) → BaseEmailBackend[source]#

Return a backend instance configured for this plugin.

Parameters:

fail_silently – Optional override for fail_silently behavior.

Returns:

A configured backend instance.

on_app_init(app_config: AppConfig) → AppConfig[source]#

Handle application initialization.

This method is called during Litestar application initialization. Registers the EmailService dependency, signature namespace entries, and app state helpers for use in handlers and event listeners.

Parameters:

app_config – The Litestar application configuration.

Returns:

The application configuration (unmodified).

class app.lib.email.EmailService(config: EmailConfig)[source]#

Bases: object

High-level helper for sending email with a configured backend.

This service is intended for dependency injection in handlers. It can also be used directly or as an async context manager to reuse connections. Outside of a context manager, each send uses a fresh backend instance.

Initialize the email service.

Parameters:

config – The email configuration.

__init__(config: EmailConfig) → None[source]#

Initialize the email service.

Parameters:

config – The email configuration.

property config: EmailConfig#

Return the email configuration.

get_backend() → BaseEmailBackend[source]#

Return a backend instance for the configured backend name.

When the service is not in a context manager, this returns a new backend instance each call.

async send_messages(messages: list[EmailMessage]) → int[source]#

Send a list of email messages.

Parameters:

messages – List of EmailMessage instances.

Returns:

Number of messages sent.

async send_message(message: EmailMessage) → int[source]#

Send a single email message.

Parameters:

message – The email message to send.

Returns:

Number of messages sent (0 or 1).

class app.lib.email.InMemoryBackend(fail_silently: bool = False, default_from_email: str | None = None, default_from_name: str | None = None)[source]#

Bases: BaseEmailBackend

Email backend that stores messages in memory.

Useful for unit and integration testing. All messages are stored in a class-level list that persists across instances.

Example

Testing with the in-memory backend:

from litestar_email.backends import InMemoryBackend

# In tests
InMemoryBackend.clear()  # Reset before test
# ... code that sends email ...
assert len(InMemoryBackend.outbox) == 1
assert InMemoryBackend.outbox[0].subject == "Welcome"

Initialize the email backend.

Parameters:
  • fail_silently – If True, exceptions during sending are suppressed.

  • default_from_email – Default sender email when message.from_email is missing.

  • default_from_name – Default sender name when message.from_email has no name.

outbox: ClassVar[list[EmailMessage]] = []#

Class-level storage for sent messages. Shared across all instances.

async send_messages(messages: list[EmailMessage]) → int[source]#

Store messages in the class-level outbox.

Parameters:

messages – List of messages to store.

Returns:

The number of messages stored.

classmethod clear() → None[source]#

Clear all stored messages.

Call this in test setup/teardown to reset state between tests.

class app.lib.email.UserProtocol(*args, **kwargs)[source]#

Bases: Protocol

Protocol for User objects used in email methods.

property email: str#

User email address.

property name: str | None#

Optional display name.

__init__(*args, **kwargs)#