Python SDK
Send emails with Python using the official Laneful Python SDK. Built for modern Python applications with async support and comprehensive features.
Templates, attachments, tracking, webhooks
Both sync and async operations
Python 3.9+ with type hints
On this page
Prerequisites
To get the most out of this guide, you'll need:
- • Python 3.9 or higher
- • pip package manager
- • A Laneful account with API key
- • Verified domain for sending emails
Installation
pip
Install the Laneful Python SDK with pip. One package gives you both the sync and async clients. This page describes version 1.2.0:
pip install laneful
Quick Start
Send your first email in minutes:
Send Simple Text Email
from laneful import LanefulClient, Email, Address
# Initialize the client
client = LanefulClient(
base_url="https://your-endpoint.z1.send.laneful.net",
auth_token="your-auth-token"
)
# Create an email
email = Email(
from_address=Address(email="sender@example.com", name="Your Name"),
to=[Address(email="recipient@example.com", name="Recipient Name")],
subject="Hello from Laneful!",
text_content="This is a simple test email sent using the Laneful Python SDK.",
html_content="<h1>Hello from Laneful!</h1><p>This is a simple test email sent using the Laneful Python SDK.</p>"
)
# Send the email
try:
response = client.send_email(email)
print("✓ Email sent successfully!")
print(f"Response status: {response.status}")
except Exception as e:
print(f"✗ Error: {e}")Replace https://your-endpoint.z1.send.laneful.net with your organization's HTTP API endpoint and your-auth-token with a private API key, both under Workspaces → Workspace Settings → API Keys in the dashboard (see Sending Email); the API accepts HTTPS only.
Examples
Common use cases and patterns:
HTML Email with Tracking
from laneful import LanefulClient, Email, Address, TrackingSettings
email = Email(
from_address=Address(email="sender@example.com", name="Your Name"),
to=[Address(email="recipient@example.com", name="Recipient Name")],
subject="HTML Email with Tracking",
html_content="<h1>Welcome!</h1><p>This is an <strong>HTML email</strong> with tracking enabled.</p>",
text_content="Welcome! This is an HTML email with tracking enabled.",
tag="welcome-email",
tracking=TrackingSettings(
opens=True,
clicks=True,
unsubscribes=True
)
)
response = client.send_email(email)Template Email
email = Email(
from_address=Address(email="sender@example.com", name="Your Name"),
to=[Address(email="user@example.com", name="User")],
subject="Welcome to Acme",
template_id="welcome-template",
template_data={
"name": "John Doe",
"company": "Acme Corporation",
"activation_link": "https://example.com/activate"
}
)
response = client.send_email(email)Email with Attachments
import base64
from laneful import LanefulClient, Email, Address, Attachment
# Create attachment from file
with open("/path/to/document.pdf", "rb") as f:
attachment_data = base64.b64encode(f.read()).decode()
email = Email(
from_address=Address(email="sender@example.com", name="Your Name"),
to=[Address(email="user@example.com", name="User")],
subject="Document Attached",
text_content="Please find the document attached.",
attachments=[
Attachment(
file_name="document.pdf",
content=attachment_data,
content_type="application/pdf"
)
]
)
response = client.send_email(email)Multiple Recipients with Reply-To
email = Email(
from_address=Address(email="sender@example.com", name="Your Name"),
to=[
Address(email="user1@example.com", name="User One"),
Address(email="user2@example.com", name="User Two")
],
cc=[Address(email="cc@example.com", name="CC Recipient")],
bcc=[Address(email="bcc@example.com", name="BCC Recipient")],
reply_to=Address(email="reply@example.com", name="Reply To"),
subject="Email to Multiple Recipients",
text_content="This email is being sent to multiple recipients."
)
response = client.send_email(email)Scheduled Email
import time
# Schedule for 24 hours from now
send_time = int(time.time()) + (24 * 60 * 60)
email = Email(
from_address=Address(email="sender@example.com", name="Your Name"),
to=[Address(email="user@example.com", name="User")],
subject="Scheduled Email",
text_content="This email was scheduled.",
send_time=send_time
)
response = client.send_email(email)Async Email Sending
import asyncio
from laneful import AsyncLanefulClient, Email, Address
async def send_async_email():
async with AsyncLanefulClient(
base_url="https://your-endpoint.z1.send.laneful.net",
auth_token="your-auth-token"
) as client:
email = Email(
from_address=Address(email="sender@example.com", name="Your Name"),
to=[Address(email="user@example.com", name="User")],
subject="Async Email",
text_content="This email was sent asynchronously.",
html_content="<h1>Async Email</h1><p>This email was sent asynchronously.</p>"
)
# Send email
try:
response = await client.send_email(email)
print("✓ Email sent successfully!")
print(f"Response status: {response.status}")
return response
except Exception as e:
print(f"✗ Error: {e}")
raise
# Run async function
asyncio.run(send_async_email())Batch Email Sending
emails = [
Email(
from_address=Address(email="sender@example.com", name="Your Name"),
to=[Address(email="user1@example.com", name="User One")],
subject="Email 1",
text_content="First email content."
),
Email(
from_address=Address(email="sender@example.com", name="Your Name"),
to=[Address(email="user2@example.com", name="User Two")],
subject="Email 2",
text_content="Second email content."
)
]
responses = client.send_emails(emails)Context Manager Usage
import asyncio
from laneful import LanefulClient, AsyncLanefulClient, Email, Address
# Sync context manager - automatic resource cleanup
with LanefulClient(
base_url="https://your-endpoint.z1.send.laneful.net",
auth_token="your-auth-token"
) as client:
email = Email(
from_address=Address(email="sender@example.com", name="Your Name"),
to=[Address(email="user@example.com", name="User")],
subject="Context Manager Email",
text_content="This email was sent using a context manager."
)
response = client.send_email(email)
print(f"Email sent: {response.status}")
# Client session automatically closed
# Async context manager (async with works only inside a coroutine)
async def main():
async with AsyncLanefulClient(
base_url="https://your-endpoint.z1.send.laneful.net",
auth_token="your-auth-token"
) as client:
email = Email(
from_address=Address(email="sender@example.com", name="Your Name"),
to=[Address(email="user@example.com", name="User")],
subject="Async Context Manager Email",
text_content="This email was sent using an async context manager."
)
response = await client.send_email(email)
print(f"Email sent: {response.status}")
# Client session automatically closed
asyncio.run(main())Webhook Handler Example
import os
from flask import Flask, request, jsonify
from laneful import WebhookVerifier
app = Flask(__name__)
WEBHOOK_SECRET = os.environ["LANEFUL_WEBHOOK_SECRET"]
@app.route('/webhook', methods=['POST'])
def handle_webhook():
# Get the raw payload: the signature covers these exact bytes
payload = request.get_data(as_text=True)
# Extract signature from headers
signature = request.headers.get('x-webhook-signature')
if not signature:
return jsonify({'error': 'Missing signature'}), 401
# Verify signature before parsing
if not WebhookVerifier.verify_signature(WEBHOOK_SECRET, payload, signature):
return jsonify({'error': 'Invalid signature'}), 401
# Parse a batch (JSON array) or a single event (JSON object)
try:
events = WebhookVerifier.parse_webhook_payload(payload)["events"]
except ValueError as e:
return jsonify({'error': str(e)}), 400
# Fields are at the top level of each event
for event in events:
event_type = event["event"]
if event_type == "request":
print(f"Email {event['message_id']} accepted for {event['email']}")
elif event_type == "delivery":
print(f"Email {event['message_id']} delivered to {event['email']}")
elif event_type == "open":
print(f"Email {event['message_id']} opened by {event['email']}")
elif event_type == "click":
print(f"Link clicked by {event['email']}: {event.get('url')}")
elif event_type == "bounce":
kind = "hard" if event.get("is_hard") else "soft"
print(f"Email bounced ({kind}) for: {event['email']}")
return jsonify({'status': 'success'})
if __name__ == '__main__':
app.run(debug=True)API Reference
LanefulClient
Constructors
- •
LanefulClient(base_url: str, auth_token: str, timeout: float = 30.0, verify_ssl: bool = True)- Initialize client with endpoint and auth token (timeout in seconds)
Methods
- •
send_email(email: Email, mail_settings: Optional[MailSettings] = None) → EmailResponse- Send single email - •
send_emails(emails: List[Email], mail_settings: Optional[MailSettings] = None) → List[EmailResponse]- Send multiple emails in one request; every item in the list holds that request's response
Required Fields
- •
from_address: Address- Sender address - •
subject: str- Email subject (also required withtemplate_id) - • At least one recipient in
to,ccorbcc, and one oftext_content,html_contentortemplate_id.Emailchecks this when you create it and raisesValueErrorif anything is missing
Optional Fields
- •
to: List[Address]- Recipient addresses - •
cc: List[Address]- CC recipient addresses - •
bcc: List[Address]- BCC recipient addresses - •
reply_to: Address- Reply-to address - •
from_header: Address- Address shown in the From header, if different fromfrom_address - •
text_content: str- Plain text content - •
html_content: str- HTML content - •
template_id: str- Template ID - •
template_data: dict- Template data - •
attachments: List[Attachment]- File attachments - •
headers: Dict[str, str]- Custom headers - •
send_time: int- Scheduled send time (Unix timestamp) - •
webhook_data: Dict[str, str]- Custom data (up to 20 keys; keys up to 50 bytes, values up to 100 bytes in UTF-8), returned unchanged asmetadataon every webhook event for this email - •
tag: str- Email tag for categorization - •
tracking: TrackingSettings- Open, click and unsubscribe tracking, all on by default
Utility Classes
- •
Address(email: str, name: str = "")- Email address with optional name - •
Attachment(content_type: str, file_name: str = "", content: str = "", inline_id: str = "")- Email attachment with base64 encoded content; setfile_nameorinline_id - •
TrackingSettings(opens: bool = True, clicks: bool = True, unsubscribes: bool = True, unsubscribe_group_id: Optional[int] = None, unsubscribe_group_name: Optional[str] = None)- Email tracking configuration - •
MailSettings(sandbox_mode: Optional[bool] = None, return_message_ids: Optional[bool] = None, idempotency_key: Optional[str] = None)- Request-level settings, passed asmail_settings.sandbox_mode: a dry run; nothing is persisted or sent.return_message_ids: getmessage_idsin the response (every email must have exactly one recipient).idempotency_key: 1 to 36 bytes (ValueErrorotherwise), see Error Handling - •
EmailResponse-status,message_id,message,message_ids. Each ID inmessage_idsmatches themessage_idon that email's webhook events - •
AsyncLanefulClient- Async version of the client for async/await operations (same arguments and methods)
WebhookVerifier
Static Methods
- •
verify_signature(secret: str, payload: str, signature: str) → bool- Verifies the HMAC-SHA256 signature of the raw body and fails safe, returningFalsewhen the secret, payload or signature is empty - •
parse_webhook_payload(payload: str) → Dict[str, Any]- Parses a batch (JSON array) or a single event intois_batchandevents(a list of full event dicts). RaisesValueErrorif the payload isn't valid JSON or any event lacks a required field. Events of types the SDK doesn't know are kept (before 1.2.0 they made the whole payload fail) - •
extract_signature_from_headers(headers: Dict[str, Any]) → Optional[str]- Reads the signature fromx-webhook-signature,X_WEBHOOK_SIGNATUREorHTTP_X_WEBHOOK_SIGNATURE
WebhookHandler
WebhookHandler(webhook_secret) routes events to handlers registered with on() or register_handler():
- •
process_webhook(payload)accepts a JSON string or bytes, a single event dict or a batch (list), and calls the handler registered for each event's type - • Register handlers with
WebhookEventTypemembers or the event names, such ason(WebhookEventType.DELIVERY)oron("delivery"). The oldemail.*names still work but are deprecated - •
verify_signature(payload, signature)returnsFalsewhen the handler has no secret - •
WebhookEventhasid,event_type,email,message_id,lane_id,tag,timestampandmetadata; event-specific fields such asurlandis_hardare indata - • Before 1.2.0,
process_webhookraisedAttributeErroron batches, theemail.*names never matched,verify_signaturereturnedTruewithout a secret anddatawas always empty. UseWebhookVerifierwith those versions
Organization API Methods
- • Unsubscribe groups:
list_unsubscribe_groups(workspace_id, ...),create_unsubscribe_group(workspace_id, ...),update_unsubscribe_group(workspace_id, unsubscribe_group_id, ...) - • Domains:
list_domains(workspace_id, ...),get_domain(workspace_id, domain),create_domain(workspace_id, ...),update_domain(workspace_id, domain, ...),verify_domain(workspace_id, domain),delete_domain(workspace_id, domain) - • Analytics:
list_domain_spam_ratio_radar,list_google_postmaster_spam_reports,list_snds_reports
These methods call the Organization API, so create a separate client with base URL https://api.laneful.net and an Organization API key (see Organization API). Domain and unsubscribe group methods are scoped to a workspace and take workspace_id: int as their first argument (the API routes them under /v1/workspaces/{workspace_id}/...). AsyncLanefulClient has the same methods.
Error Handling
Comprehensive error handling with specific exception types:
from laneful.exceptions import LanefulError, LanefulAPIError, LanefulAuthError
try:
response = client.send_email(email)
print("✓ Email sent successfully!")
print(f"Response status: {response.status}")
except LanefulAuthError:
print("✗ Authentication failed - check your API token")
except LanefulAPIError as e:
print(f"✗ API error: {e.message} (status: {e.status_code})")
except LanefulError as e:
print(f"✗ Client error: {e.message}")
except Exception as e:
print(f"✗ Unexpected error: {e}")Error Handling
- •
LanefulAuthError- Authentication failures - •
LanefulAPIError- API request failures - •
LanefulError- General client errors - •
Exception- Unexpected errors
Best Practices
- • Always wrap API calls in try-except
- • Handle specific exception types first
- • Log errors with context information
- • The SDK doesn't retry on its own. A request that timed out may already have been accepted, so when you retry a send, reuse the same
idempotency_key(see below)
Duplicate Send Protection
Pass an idempotency_key (1 to 36 bytes, see Sending Email) and reuse it when you retry a send, for example after a timeout:
from laneful import MailSettings
settings = MailSettings(idempotency_key=f"order-{order_id}-receipt")
response = client.send_email(email, settings)Laneful remembers a key per organization for one hour. A repeated request with the same key returns status accepted with no message IDs and sends nothing, even if the emails differ, so use a new key for every distinct send. Detection is best effort. A request that fails with HTTP 500 doesn't keep its key, so a retry with it is processed as a new request: before resending after a 500, check your webhook events (a request event means Laneful accepted the email). Sandbox mode requests aren't deduplicated. Requires 1.2.0 or later.
Webhook Handling
WebhookVerifier verifies signatures and parses payloads, single events and batches alike. Laneful signs the raw request body with HMAC-SHA256 and sends the signature in the X-Webhook-Signature header as 64 lowercase hex characters with no prefix, so verify the body exactly as received, before parsing it. Event fields are at the top level of each event, and metadata holds the webhook_data you sent with the email; see Webhooks for every field. The examples expect the Laneful payload format (the default). WebhookHandler also processes batches from 1.2.0 (see API Reference).
Basic Signature Verification
import os
from flask import Flask, request, jsonify
from laneful import WebhookVerifier
app = Flask(__name__)
WEBHOOK_SECRET = os.environ["LANEFUL_WEBHOOK_SECRET"]
@app.route('/webhook', methods=['POST'])
def handle_webhook():
payload = request.get_data(as_text=True) # Get the raw request body
signature = request.headers.get('x-webhook-signature', '')
if not WebhookVerifier.verify_signature(WEBHOOK_SECRET, payload, signature):
# Invalid signature
return jsonify({'error': 'Invalid signature'}), 401
# Process webhook data (see Advanced Webhook Processing)
return jsonify({'status': 'success'})Advanced Webhook Processing
import os
from flask import Flask, request, jsonify
from laneful import WebhookVerifier
app = Flask(__name__)
WEBHOOK_SECRET = os.environ["LANEFUL_WEBHOOK_SECRET"]
# Event handlers receive the full event dict
def handle_request_event(event):
print(f"Email {event['message_id']} accepted for {event['email']}")
def handle_delivery_event(event):
# metadata is the webhook_data sent with the email
print(f"Email {event['message_id']} delivered to {event['email']}: {event.get('metadata')}")
def handle_open_event(event):
print(f"Email {event['message_id']} opened by {event['email']}")
def handle_click_event(event):
print(f"Link clicked by {event['email']}: {event.get('url')}")
def handle_bounce_event(event):
kind = "hard" if event.get("is_hard") else "soft"
print(f"Email bounced ({kind}) for: {event['email']}")
def handle_drop_event(event):
print(f"Email to {event['email']} dropped: {event.get('reason')}")
def handle_spam_complaint_event(event):
print(f"Spam complaint from {event['email']}")
def handle_unsubscribe_event(event):
print(f"Unsubscribe from {event['email']} (group {event.get('unsubscribe_group_id')})")
EVENT_HANDLERS = {
"request": handle_request_event,
"delivery": handle_delivery_event,
"open": handle_open_event,
"click": handle_click_event,
"bounce": handle_bounce_event,
"drop": handle_drop_event,
"spam_complaint": handle_spam_complaint_event,
"unsubscribe": handle_unsubscribe_event,
}
@app.route('/webhook', methods=['POST'])
def handle_webhook():
# Step 1: Get raw payload
payload = request.get_data(as_text=True)
# Step 2: Extract signature from headers
signature = request.headers.get('x-webhook-signature')
if not signature:
return jsonify({'error': 'Missing signature'}), 401
# Step 3: Verify signature
if not WebhookVerifier.verify_signature(WEBHOOK_SECRET, payload, signature):
return jsonify({'error': 'Invalid signature'}), 401
# Step 4: Parse a batch (JSON array) or a single event
try:
parsed = WebhookVerifier.parse_webhook_payload(payload)
except ValueError as e:
# Payload validation error
return jsonify({'error': str(e)}), 400
# Step 5: Dispatch each event on its "event" value
for event in parsed["events"]:
handler = EVENT_HANDLERS.get(event["event"])
if handler:
handler(event)
return jsonify({'status': 'success'})Batch Mode Support
With batch mode on, the request body is a JSON array of events; with it off, it is a single event object. parse_webhook_payload accepts both and returns {"is_batch": ..., "events": [...]}, so the same code handles both modes. Events of types not listed below are kept, so dispatch on event["event"] and skip the ones you don't handle (before 1.2.0, one unknown type made the whole payload fail).
Supported Webhook Events
Delivery Events
- •
request- Email accepted and queued for delivery - •
delivery- Email delivered successfully - •
bounce- Email bounced (hard or soft) - •
drop- Email not sent (for example, the address is suppressed) - •
spam_complaint- Recipient marked email as spam
Engagement Events
- •
open- Email opened by recipient - •
click- Link clicked in email - •
unsubscribe- Recipient unsubscribed
Each temporary delivery failure arrives as a bounce with is_hard: false; there is no separate deferral event.
Webhook Features
Security
- • HMAC-SHA256 signature verification
- • Accepts the signature with or without a
sha256=prefix (Laneful sends none) - • Constant-time comparison (timing attack protection)
- • Multiple header format support
Validation (parse_webhook_payload)
- • JSON payload structure validation
- • Required fields:
event,email,lane_id,message_id,timestamp - • Event type is one of the 8 above
- • Email contains
@ - • Numeric timestamp
Ready to Get Started?
Start sending emails with Python in minutes. Check out the examples and integrate with your application.