email#
Transactional React Email service wrapper.
Email module wrapping litestar-email with template-backed AppEmailService.
- class app.lib.email.AppEmailService(mailer: EmailService)[source]#
Bases:
objectTemplate-rendering transactional email adapter over
litestar-emailEmailService.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.
- 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:
Trueif 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:
Trueif the message was sent.
- async send_welcome_email(user: UserProtocol) bool[source]#
Send a welcome message to a newly verified user.
- Returns:
Trueif 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:
Trueif the message was sent.
- async send_password_reset_confirmation_email(user: UserProtocol) bool[source]#
Send a password reset confirmation message.
- Returns:
Trueif 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:
objectConfiguration 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:
objectA 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:
EmailMessageAn email message with HTML content support.
This convenience class extends EmailMessage to automatically attach an HTML body as an alternative representation.
- __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:
InitPluginProtocolLitestar 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:
objectHigh-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:
BaseEmailBackendEmail 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.