LettermintLettermint
  • Knowledge base
  • Community
  • Changelog
  • Support
  • Documentation
  • Sending API
  • Team API
Getting started
Guides
    Node.jsPHPPythonGoLaravelMagento 2WordPressNuxtJava
    SMTP
Platform
Resources
Guides

Python

The official Lettermint Python SDK sends email through a fluent, chainable API with both synchronous and async clients. You build a message step by step and call send(), so it fits neatly into scripts, web frameworks like Django and Flask, and async stacks like FastAPI and Starlette.

Every message is delivered through Lettermint's European infrastructure, which runs entirely inside the EU and processes mail in line with GDPR. That makes the SDK a solid choice for transactional email from a Python app, such as order confirmations, password resets, and account notifications.

Requirements

Before you start you need:

  • Python 3.9 or newer
  • A Lettermint account with a verified sending domain
  • A Project API token from your project settings

If your domain is not verified yet, follow the domain setup guide first so your mail reaches the inbox instead of the spam folder.

1. Installation

Install the SDK via pip:

2. Send your first email

Initialize the client with your Project API token:

Code
import os from lettermint import Lettermint client = Lettermint(api_token=os.environ.get("LETTERMINT_PROJECT_TOKEN"))

Send your first email:

Code
response = ( client.email .from_("John Doe <john@yourdomain.com>") .to("recipient@example.com") .subject("Hello from Lettermint") .text("This is a test email sent using the Lettermint Python SDK.") .send() ) print(f"Email sent with ID: {response['message_id']}")

3. Email Features

Basic Email

Send a simple text or HTML email:

Code
response = ( client.email .from_("John Doe <john@yourdomain.com>") .to("recipient@example.com") .subject("Your account is ready!") .html("<h1>Welcome!</h1><p>Thanks for signing up.</p>") .text("Welcome! Thanks for signing up.") .send() )

Multiple Recipients

Send to multiple recipients using CC and BCC:

Code
response = ( client.email .from_("John Doe <john@yourdomain.com>") .to("user1@example.com", "user2@example.com") .cc("manager@yourdomain.com") .bcc("archive@yourdomain.com") .subject("Monthly Newsletter") .html("<h1>This Month's Updates</h1>") .send() )

Custom Headers and Reply-To

Add custom headers and set reply-to addresses:

Code
response = ( client.email .from_("support@yourdomain.com") .to("customer@example.com") .reply_to("help@yourdomain.com") .subject("Support Ticket #12345") .headers({ "X-Priority": "1", "X-Ticket-ID": "12345" }) .html("<p>Your support ticket has been updated.</p>") .send() )

Metadata

Add metadata for tracking and webhook payloads:

Code
response = ( client.email .from_("notifications@yourdomain.com") .to("user@example.com") .subject("Order Confirmation") .metadata({ "order_id": "12345", "customer_id": "cust_789", "campaign": "order_confirmation" }) .html("<p>Your order has been confirmed.</p>") .send() )

Metadata is included in webhook payloads but not added to the actual email headers. Use it for tracking and analytics purposes.

Tags

Categorize emails for filtering and analytics:

Code
response = ( client.email .from_("alerts@yourdomain.com") .to("admin@example.com") .subject("System Alert") .tag("system-alerts") .html("<p>Critical system alert detected.</p>") .send() )

One tag per message. Tags can contain letters, numbers, hyphens, underscores, and spaces (max 255 characters). See Tags documentation for more details.

Route Selection

Direct emails to specific routes within your project:

Code
response = ( client.email .from_("notifications@yourdomain.com") .to("user@example.com") .subject("Welcome!") .route("transactional") .html("<p>Welcome to our platform.</p>") .send() )

File Attachments

Attach files to your emails:

Code
import base64 # Read and encode file with open("/path/to/document.pdf", "rb") as f: encoded_content = base64.b64encode(f.read()).decode() response = ( client.email .from_("invoices@yourdomain.com") .to("customer@example.com") .subject("Your Invoice") .html("<p>Please find your invoice attached.</p>") .attach("invoice.pdf", encoded_content) .send() )

Inline Images

Embed images directly in your HTML using Content-ID:

Code
import base64 with open("/path/to/logo.png", "rb") as f: encoded_logo = base64.b64encode(f.read()).decode() response = ( client.email .from_("marketing@yourdomain.com") .to("customer@example.com") .subject("Welcome to Our Platform") .html('<p>Welcome!</p><img src="cid:logo@yourdomain.com" alt="Logo">') .attach("logo.png", encoded_logo, "logo@yourdomain.com") .send() )

Idempotency

Prevent duplicate emails with idempotency keys:

Code
response = ( client.email .from_("notifications@yourdomain.com") .to("user@example.com") .subject("Order Confirmation") .html("<p>Your order has been confirmed.</p>") .idempotency_key("order-12345-confirmation") .send() )

Use a unique key per logical email (e.g., combining order ID + email type). Retrying with the same key won't send duplicate emails.

4. Send an order confirmation

A real transactional send usually pulls several of these features together. This example sends a receipt with an HTML and plain-text body, tags it for analytics, attaches the order and customer IDs as metadata, and uses an idempotency key so a retry never emails the customer twice:

Code
import os from lettermint import Lettermint client = Lettermint(api_token=os.environ.get("LETTERMINT_PROJECT_TOKEN")) def send_order_confirmation(order): return ( client.email .from_("Acme Store <orders@yourdomain.com>") .to(order["customer_email"]) .reply_to("support@yourdomain.com") .subject(f"Order {order['number']} confirmed") .html(f"<h1>Thanks for your order</h1><p>Order {order['number']} totalling {order['total']} is confirmed.</p>") .text(f"Thanks for your order. Order {order['number']} totalling {order['total']} is confirmed.") .tag("order-confirmation") .metadata({"order_id": order["id"], "customer_id": order["customer_id"]}) .idempotency_key(f"order-confirmation-{order['id']}") .route("transactional") .send() )

The metadata you attach here travels with every webhook event for the message, so a later delivery or bounce maps straight back to the order in your database.

5. Async Support

The SDK provides an async client for use with asyncio:

Code
import asyncio import os from lettermint import AsyncLettermint async def send_email(): async with AsyncLettermint(api_token=os.environ.get("LETTERMINT_PROJECT_TOKEN")) as client: response = await ( client.email .from_("John Doe <john@yourdomain.com>") .to("recipient@example.com") .subject("Hello from Lettermint") .text("This is a test email.") .send() ) print(f"Email sent with ID: {response['message_id']}") asyncio.run(send_email())

Use the async client in FastAPI, Starlette, or other async frameworks for better performance.

6. Client Configuration

Customize the client with optional parameters:

Code
client = Lettermint( api_token=os.environ.get("LETTERMINT_PROJECT_TOKEN"), base_url="https://api.lettermint.co/v1", # Custom API URL timeout=60.0, # Request timeout in seconds )

Use the client as a context manager for automatic resource cleanup:

Code
with Lettermint(api_token=os.environ.get("LETTERMINT_PROJECT_TOKEN")) as client: response = ( client.email .from_("sender@yourdomain.com") .to("recipient@example.com") .subject("Test") .text("Hello!") .send() )

7. Response

Code
response = ( client.email .from_("John Doe <john@yourdomain.com>") .to("recipient@example.com") .subject("Test") .text("Hello!") .send() ) print(response["message_id"]) # Unique email ID

8. Error Handling

Handle errors with specific exception types:

Code
from lettermint import Lettermint from lettermint.exceptions import ( ValidationError, ClientError, TimeoutError, HttpRequestError, ) client = Lettermint(api_token=os.environ.get("LETTERMINT_PROJECT_TOKEN")) try: response = ( client.email .from_("sender@yourdomain.com") .to("recipient@example.com") .subject("Test") .text("Hello!") .send() ) except ValidationError as e: # 422 errors (invalid parameters, daily limit exceeded, etc.) print(f"Validation error: {e.error_type}") except ClientError as e: # 400 errors (bad request) print(f"Client error: {e}") except TimeoutError as e: # Request timed out print(f"Timeout: {e}") except HttpRequestError as e: # Other HTTP errors print(f"HTTP error {e.status_code}: {e}")

Track delivery, opens, and bounces

Sending is only half of a transactional setup. To see what happens after a message leaves your app, combine the SDK with Lettermint's platform features:

  • Email tracking records opens and clicks, with bot filtering so your metrics stay accurate.
  • Webhooks push delivery, bounce, and complaint events to your server in real time, so you can update order records or suppress bad addresses.
  • Test addresses let you trigger a hard or soft bounce on demand while you build and verify your webhook handler.

Tracking is configured per route, so turn it on for the route your app sends through, then read the results from your dashboard or your webhook endpoint.

FAQ

Does the SDK support async?

Yes. Import AsyncLettermint and use it with asyncio. It works well inside async frameworks such as FastAPI and Starlette, and the builder API is identical to the synchronous client.

How do I stop the same email being sent twice?

Add an idempotency key with .idempotency_key(), derived from a stable ID such as an order number. A repeated request with the same key returns the original result instead of sending again. See the idempotency documentation.

Is Lettermint email GDPR compliant and EU-hosted?

Yes. Lettermint runs exclusively on European infrastructure and processes email in line with GDPR, so transactional mail from your Python app is handled inside the EU.

How do I track opens, clicks, and bounces?

Enable tracking on your route and subscribe to webhooks to receive delivery, open, and bounce events. Use the test addresses to simulate bounces while you build your handler.

Next Steps

Tags

Organize and filter emails with tags.

Tracking

Track opens, clicks, and deliverability.

Webhooks

Receive real-time delivery notifications.

SMTP Alternative

Send via SMTP instead of the API.

GitHub Repository

Find the complete source code, report issues, or contribute on GitHub.

Last modified on August 7, 2026
PHPGo
On this page
  • Requirements
  • 1. Installation
  • 2. Send your first email
  • 3. Email Features
    • Basic Email
    • Multiple Recipients
    • Custom Headers and Reply-To
    • Metadata
    • Tags
    • Route Selection
    • File Attachments
    • Inline Images
    • Idempotency
  • 4. Send an order confirmation
  • 5. Async Support
  • 6. Client Configuration
  • 7. Response
  • 8. Error Handling
  • Track delivery, opens, and bounces
  • FAQ
  • Next Steps
pip install lettermint