API Reference¶
The main public API is exported through the litestar_email module.
All classes, functions, and exceptions are available at the top level.
Configuration¶
- class litestar_email.config.AsyncServiceProvider(config: EmailConfig)[source]¶
Bases:
objectProvides EmailService as an async context manager.
This class enables managed usage of the email service with automatic connection handling:
Example:
async with config.provide_service() as mailer: await mailer.send_message(message)
- __init__(config: EmailConfig) None[source]¶
Initialize the service provider.
- Parameters:
config – The email configuration.
- litestar_email.config.BackendConfig = litestar_email.config.SMTPConfig | litestar_email.config.ResendConfig | litestar_email.config.SendGridConfig | litestar_email.config.MailgunConfig¶
Type alias for all backend configuration types.
- class litestar_email.config.EmailConfig(backend: str | SMTPConfig | ResendConfig | SendGridConfig | MailgunConfig = '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", )
- backend: str | SMTPConfig | ResendConfig | SendGridConfig | MailgunConfig¶
- 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 = '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 litestar_email.config.MailgunConfig(api_key: str = '', domain: str = '', region: str = 'us', timeout: int = 30, http_transport: str | type[HTTPTransport] = 'httpx')[source]¶
Bases:
objectConfiguration for Mailgun API email backend.
This configuration class defines the settings for the Mailgun API email service (https://mailgun.com).
Example
Configure with API key and domain:
config = MailgunConfig( api_key="key-xxx...", domain="mg.example.com", )
Configure for EU region:
config = MailgunConfig( api_key="key-xxx...", domain="mg.example.com", region="eu", )
Use aiohttp transport:
config = MailgunConfig( api_key="key-xxx...", domain="mg.example.com", http_transport="aiohttp", )
- class litestar_email.config.ResendConfig(api_key: str = '', timeout: int = 30, http_transport: str | type[HTTPTransport] = 'httpx')[source]¶
Bases:
objectConfiguration for Resend API email backend.
This configuration class defines the settings for the Resend API email service (https://resend.com).
Example
Configure with an API key:
config = ResendConfig(api_key="re_123abc...")Use aiohttp transport:
config = ResendConfig( api_key="re_123abc...", http_transport="aiohttp", )
- class litestar_email.config.SMTPConfig(host: str = 'localhost', port: int = 25, username: str | None = None, password: str | None = None, use_tls: bool = False, use_ssl: bool = False, timeout: int = 30)[source]¶
Bases:
objectConfiguration for SMTP email backend.
This configuration class defines the settings for connecting to an SMTP server for sending email.
Example
Configure for a local Mailpit instance:
config = SMTPConfig(host="localhost", port=1025)Configure for a production server with TLS:
config = SMTPConfig( host="smtp.example.com", port=587, username="user@example.com", password="secret", use_tls=True, )
- class litestar_email.config.SendGridConfig(api_key: str = '', timeout: int = 30, http_transport: str | type[HTTPTransport] = 'httpx')[source]¶
Bases:
objectConfiguration for SendGrid API email backend.
This configuration class defines the settings for the SendGrid API email service (https://sendgrid.com).
Example
Configure with an API key:
config = SendGridConfig(api_key="SG.xxx...")Use aiohttp transport:
config = SendGridConfig( api_key="SG.xxx...", http_transport="aiohttp", )
Messages¶
- class litestar_email.message.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 litestar_email.message.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¶
Service¶
- class litestar_email.service.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.
- __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).
Plugin¶
- class litestar_email.plugin.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]), )
- __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).
Exceptions¶
Email exception hierarchy.
This module defines custom exceptions for the litestar-email plugin, providing specific exception types for different failure modes.
- exception litestar_email.exceptions.EmailAuthenticationError[source]¶
Bases:
EmailDeliveryErrorError authenticating with email server or API.
Raised when authentication fails with the SMTP server (invalid username/password) or API service (invalid API key).
Example
Handle authentication failures:
try: await backend.send_messages([message]) except EmailAuthenticationError as e: logger.error(f"Authentication failed: {e}") # Do not retry - credentials need to be fixed
- exception litestar_email.exceptions.EmailBackendError[source]¶
Bases:
EmailErrorError in email backend configuration or initialization.
Raised when there is a problem with the email backend setup, such as missing dependencies, invalid configuration, or backend initialization failures.
Example
Handle backend configuration errors:
try: backend = get_backend("smtp", config=config) except EmailBackendError as e: logger.error(f"Backend setup failed: {e}")
- exception litestar_email.exceptions.EmailConnectionError[source]¶
Bases:
EmailDeliveryErrorError connecting to email server or API.
Raised when the email backend cannot establish a connection to the SMTP server or API endpoint. This could be due to network issues, invalid hostnames, or server unavailability.
Example
Handle connection failures with retry:
try: await backend.send_messages([message]) except EmailConnectionError as e: logger.warning(f"Connection failed, retrying: {e}") await asyncio.sleep(5) # retry logic...
- exception litestar_email.exceptions.EmailDeliveryError[source]¶
Bases:
EmailErrorError during email delivery.
Base class for errors that occur while attempting to send email messages. This includes connection, authentication, and rate limit errors.
Example
Handle delivery failures:
try: await backend.send_messages([message]) except EmailDeliveryError as e: logger.error(f"Delivery failed: {e}")
- exception litestar_email.exceptions.EmailError[source]¶
Bases:
ExceptionBase exception for all email-related errors.
This is the root exception class for the litestar-email plugin. All other email exceptions inherit from this class, allowing users to catch all email-related errors with a single handler.
Example
Catch all email errors:
try: await backend.send_messages([message]) except EmailError as e: logger.error(f"Email failed: {e}")
- exception litestar_email.exceptions.EmailRateLimitError(message: str, retry_after: int | None = None)[source]¶
Bases:
EmailDeliveryErrorRate limit exceeded for email API.
Raised when the email API service returns a rate limit error (typically HTTP 429). This is common with API-based backends like Resend and SendGrid.
Example
Handle rate limits with exponential backoff:
try: await backend.send_messages([message]) except EmailRateLimitError as e: wait_time = e.retry_after or 60 logger.warning(f"Rate limited, waiting {wait_time}s") await asyncio.sleep(wait_time) # retry logic...
- exception litestar_email.exceptions.MissingDependencyError(package: str, install_package: str | None = None)[source]¶
Bases:
EmailError,ImportErrorRaised when a required optional dependency is not installed.
This exception inherits from both EmailError (for catch-all email error handling) and ImportError (for semantic correctness when a dependency import fails).
Example
Handle missing dependency errors:
try: from litestar_email.backends.smtp import SMTPBackend backend = SMTPBackend(config=config) except MissingDependencyError as e: logger.error(f"Missing dependency: {e}") # Install the dependency or use a different backend
Backends¶
The backends are available via litestar_email.backends. Use
get_backend() or get_backend_class() to obtain backend instances.
- litestar_email.backends.get_backend(backend: str | BackendConfig = 'console', fail_silently: bool | None = None, config: EmailConfig | None = None) BaseEmailBackend[source]¶
Get an instantiated backend by name or config object.
- Parameters:
backend – Either a backend short name (e.g., “console”, “smtp”), a full import path, or a backend config object (SMTPConfig, ResendConfig, etc.).
fail_silently – Whether the backend should suppress exceptions. If None, uses config.fail_silently when config is provided.
config – Optional EmailConfig to extract common settings from (from_email, from_name, fail_silently).
- Returns:
An instantiated backend.
Note
May raise
MissingDependencyErrorif the backend requires a package that is not installed.Example
Basic usage:
backend = get_backend("console") async with backend: await backend.send_messages([message])
With config object:
backend = get_backend(SMTPConfig(host="localhost", port=1025))From EmailConfig:
config = EmailConfig( backend=ResendConfig(api_key="re_xxx..."), fail_silently=True, ) backend = get_backend(config.backend, config=config)
- litestar_email.backends.get_backend_class(backend_path: str) type[BaseEmailBackend][source]¶
Get a backend class by short name or full import path.
- Parameters:
backend_path – Either a registered short name (e.g., “console”, “memory”) or a full Python import path (e.g., “myapp.backends.CustomBackend”).
- Returns:
The backend class.
- Raises:
ValueError – If the backend cannot be found.
Example
Getting a backend class:
# By short name cls = get_backend_class("console") # By full path cls = get_backend_class("litestar_email.backends.console.ConsoleBackend")
- litestar_email.backends.register_backend(name: str) type[BaseEmailBackend][source]¶
Decorator to register a backend class with a short name.
- Parameters:
name – The short name for the backend (e.g., “console”, “smtp”).
- Returns:
A decorator that registers the backend class.
Example
Registering a custom backend:
@register_backend("mybackend") class MyBackend(BaseEmailBackend): async def send_messages(self, messages): ...
- litestar_email.backends.list_backends() list[str][source]¶
Return a list of registered backend short names.
- Returns:
A list of backend names that can be used with get_backend().
- class litestar_email.backends.base.BaseEmailBackend(fail_silently: bool = False, default_from_email: str | None = None, default_from_name: str | None = None)[source]¶
Bases:
ABCAbstract base class for email backends.
All email backends must inherit from this class and implement the
send_messagesmethod. Backends can optionally overrideopenandclosefor connection pooling.The class supports async context manager protocol for resource management.
Example
Basic usage with context manager:
async with get_backend() as backend: await backend.send_messages([message])
- __init__(fail_silently: bool = False, default_from_email: str | None = None, default_from_name: str | None = None) None[source]¶
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.
- fail_silently¶
- async open() bool[source]¶
Open a connection to the email server.
Override this method to implement connection pooling. Called automatically when entering the async context manager.
- Returns:
True if connection was opened, False if already open or not needed.
- async close() None[source]¶
Close the connection to the email server.
Override this method to clean up resources. Called automatically when exiting the async context manager.
- abstractmethod async send_messages(messages: list[EmailMessage]) int[source]¶
Send one or more email messages.
This method must be implemented by all backends.
- Parameters:
messages – A list of EmailMessage instances to send.
- Returns:
The number of messages successfully sent.
- Raises:
Exception – If fail_silently is False and sending fails.
- class litestar_email.backends.console.ConsoleBackend(fail_silently: bool = False, stream: TextIO | None = None, default_from_email: str | None = None, default_from_name: str | None = None)[source]¶
Bases:
BaseEmailBackendEmail backend that writes messages to a stream (default: stdout).
Useful for local development and debugging. Prints email metadata and content to the console in a human-readable format.
Example
Basic configuration:
from litestar_email import EmailConfig config = EmailConfig(backend="console")
- __init__(fail_silently: bool = False, stream: TextIO | None = None, default_from_email: str | None = None, default_from_name: str | None = None) None[source]¶
Initialize the console backend.
- Parameters:
fail_silently – If True, exceptions are suppressed.
stream – Output stream. Defaults to sys.stdout.
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.
- stream¶
- async send_messages(messages: list[EmailMessage]) int[source]¶
Write email messages to the stream.
- Parameters:
messages – List of messages to output.
- Returns:
The number of messages written.
- class litestar_email.backends.memory.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"
- 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.
Async SMTP email backend using aiosmtplib.
- class litestar_email.backends.smtp.SMTPBackend(config: SMTPConfig | None = None, fail_silently: bool = False, default_from_email: str | None = None, default_from_name: str | None = None)[source]¶
Bases:
BaseEmailBackendAsync SMTP email backend using aiosmtplib.
This backend provides true async email sending without blocking the event loop. It supports connection pooling through the context manager protocol, TLS/SSL, and authentication.
The backend requires the
aiosmtplibpackage to be installed. Install it with:pip install litestar-email[smtp]Example
Basic usage with Mailpit (local development):
config = EmailConfig( backend="smtp", from_email="noreply@example.com", backend_config=SMTPConfig(host="localhost", port=1025), ) backend = get_backend("smtp", config=config) async with backend: await backend.send_messages([message])
Production usage with STARTTLS:
config = EmailConfig( backend="smtp", from_email="noreply@example.com", backend_config=SMTPConfig( host="smtp.example.com", port=587, username="user@example.com", password="secret", use_tls=True, ), )
- __init__(config: SMTPConfig | None = None, fail_silently: bool = False, default_from_email: str | None = None, default_from_name: str | None = None) None[source]¶
Initialize SMTP backend.
- Parameters:
config – SMTP configuration settings. If None, defaults are used.
fail_silently – If True, suppress exceptions during send.
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.
Note
May raise
MissingDependencyErrorif aiosmtplib is not installed.
- async open() bool[source]¶
Open a connection to the SMTP server.
- Returns:
True if a new connection was opened, False if reusing existing.
- Raises:
EmailConnectionError – If connection to the server fails.
EmailAuthenticationError – If authentication fails.
- async send_messages(messages: list[EmailMessage]) int[source]¶
Send messages via SMTP.
If not already connected, opens a connection for the duration of the send operation.
- Parameters:
messages – List of EmailMessage instances to send.
- Returns:
Number of messages successfully sent.
- Raises:
EmailDeliveryError – If sending fails and fail_silently is False.
Resend email backend using the Resend HTTP API.
- class litestar_email.backends.resend.ResendBackend(config: ResendConfig | None = None, fail_silently: bool = False, default_from_email: str | None = None, default_from_name: str | None = None)[source]¶
Bases:
BaseEmailBackendResend email backend using the HTTP API.
This backend sends emails via Resend’s HTTP API, which doesn’t require SMTP ports and works on any hosting plan.
The backend uses httpx by default (bundled with Litestar), but can be configured to use aiohttp or a custom HTTP transport.
Example
Basic usage:
config = EmailConfig( backend="resend", from_email="noreply@example.com", backend_config=ResendConfig(api_key="re_xxx..."), ) backend = get_backend("resend", config=config) async with backend: await backend.send_messages([message])
Using aiohttp transport:
config = EmailConfig( backend="resend", from_email="noreply@example.com", backend_config=ResendConfig( api_key="re_xxx...", http_transport="aiohttp", ), )
Get your API key at: https://resend.com/api-keys
- __init__(config: ResendConfig | None = None, fail_silently: bool = False, default_from_email: str | None = None, default_from_name: str | None = None) None[source]¶
Initialize Resend backend.
- Parameters:
config – Resend configuration settings. If None, defaults are used.
fail_silently – If True, suppress exceptions during send.
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.
Note
May raise
MissingDependencyErrorif the configured HTTP transport is not installed.
- async open() bool[source]¶
Open an HTTP transport for sending emails.
- Returns:
True if a new transport was created, False if reusing existing.
- async send_messages(messages: list[EmailMessage]) int[source]¶
Send messages via Resend API.
- Parameters:
messages – List of EmailMessage instances to send.
- Returns:
Number of messages successfully sent.
- Raises:
EmailDeliveryError – If sending fails and fail_silently is False.
EmailRateLimitError – If rate limited by the API.
SendGrid email backend using the SendGrid v3 HTTP API.
- class litestar_email.backends.sendgrid.SendGridBackend(config: SendGridConfig | None = None, fail_silently: bool = False, default_from_email: str | None = None, default_from_name: str | None = None)[source]¶
Bases:
BaseEmailBackendSendGrid email backend using the v3 HTTP API.
This backend sends emails via SendGrid’s HTTP API, which doesn’t require SMTP ports and works on any hosting plan.
The backend uses httpx by default (bundled with Litestar), but can be configured to use aiohttp or a custom HTTP transport.
Example
Basic usage:
config = EmailConfig( backend="sendgrid", from_email="noreply@example.com", backend_config=SendGridConfig(api_key="SG.xxx..."), ) backend = get_backend("sendgrid", config=config) async with backend: await backend.send_messages([message])
Using aiohttp transport:
config = EmailConfig( backend="sendgrid", from_email="noreply@example.com", backend_config=SendGridConfig( api_key="SG.xxx...", http_transport="aiohttp", ), )
Get your API key at: https://app.sendgrid.com/settings/api_keys
- __init__(config: SendGridConfig | None = None, fail_silently: bool = False, default_from_email: str | None = None, default_from_name: str | None = None) None[source]¶
Initialize SendGrid backend.
- Parameters:
config – SendGrid configuration settings. If None, defaults are used.
fail_silently – If True, suppress exceptions during send.
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.
Note
May raise
MissingDependencyErrorif the configured HTTP transport is not installed.
- async open() bool[source]¶
Open an HTTP transport for sending emails.
- Returns:
True if a new transport was created, False if reusing existing.
- async send_messages(messages: list[EmailMessage]) int[source]¶
Send messages via SendGrid API.
- Parameters:
messages – List of EmailMessage instances to send.
- Returns:
Number of messages successfully sent.
- Raises:
EmailDeliveryError – If sending fails and fail_silently is False.
EmailRateLimitError – If rate limited by the API.