Rust SDK
Send emails with Rust using the official Laneful Rust SDK. Built for performance and safety with async support.
Templates, attachments, tracking, webhooks
Optional async API for tokio
rustls (default) or native-tls
On this page
Prerequisites
To get the most out of this guide, you'll need:
- • Rust 1.85 or higher (the crate uses edition 2024)
- • Cargo package manager
- • A Laneful account with API key
- • Verified domain for sending emails
Installation
Using Cargo
Add the Laneful Rust SDK to your project:
cargo add laneful-rs
Or add to Cargo.toml
laneful-rs = "0.3"
Async API
Enable async support with the async feature, and add tokio for the runtime the async methods run on:
laneful-rs = { version = "0.3", features = ["async"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }TLS Backend
The SDK uses rustls by default. To use native-tls instead (add "async" to the features if you need it):
laneful-rs = { version = "0.3", default-features = false, features = ["native-tls"] }Crates Used in the Examples
serde_json = "1" # template data, webhooks base64 = "0.22" # attachments axum = "0.8" # webhook handler (with tokio)
Quick Start
Send your first email in minutes:
Send Simple Text Email
use laneful_rs::{Email, LanefulClient};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create client
let client = LanefulClient::new(
"https://your-endpoint.z1.send.laneful.net",
"your-api-key",
)?;
// Create email
let email = Email::builder()
.from("sender@example.com", Some("Your Name"))
.to("recipient@example.com", Some("Recipient Name"))
.subject("Hello from Laneful!")
.text_content("This is a simple test email sent using the Laneful Rust SDK.")
.build()?;
// Send email
let response = client.send_one(email)?;
println!("✓ Email sent successfully! Status: {:?}", response);
Ok(())
}Replace https://your-endpoint.z1.send.laneful.net with your organization's HTTP API endpoint, shown in the dashboard under Workspaces → Workspace Settings → API Keys (see Sending Email), and your-api-key with a key you create there. The API accepts HTTPS only.
Examples
Common use cases and patterns. Each snippet except the async example builds on Quick Start: it uses that client and runs inside a function that returns Result<(), Box<dyn std::error::Error>>:
Async Email Sending
From 0.3.0 a client used only through async methods can be created and dropped inside a Tokio runtime: the blocking HTTP client is built on the first sync call. In 0.2, LanefulClient::new builds the blocking client right away, which panics inside an async runtime, so create it before starting the runtime or with tokio::task::spawn_blocking.
use laneful_rs::{Email, LanefulClient};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = LanefulClient::new("https://your-endpoint.z1.send.laneful.net", "your-api-key")?;
let email = Email::builder()
.from("sender@example.com", Some("Sender"))
.to("recipient@example.com", Some("Recipient"))
.subject("Hello from Laneful (async)!")
.text_content("This is a test email.")
.build()?;
let response = client.send_one_async(email).await?;
println!("Sent: {:?}", response);
Ok(())
}HTML Email with Tracking
use laneful_rs::{Email, Tracking};
let email = Email::builder()
.from("sender@example.com", Some("Your Name"))
.to("recipient@example.com", Some("Recipient Name"))
.subject("HTML Email with Tracking")
.html_content("<h1>Welcome!</h1><p>This is an <strong>HTML email</strong> with tracking.</p>")
.text_content("Welcome! This is an HTML email with tracking enabled.")
.tracking(Tracking {
opens: Some(true),
clicks: Some(true),
..Default::default()
})
.tag("welcome-email")
.build()?;
let response = client.send_one(email)?;Template Email
use serde_json::json;
let email = Email::builder()
.from("sender@example.com", None)
.to("user@example.com", None)
.subject("Welcome to Acme!")
.template_id("welcome-template")
.template_data(json!({
"name": "John Doe",
"company": "Acme Corporation",
"activation_link": "https://example.com/activate"
}))
.build()?;
let response = client.send_one(email)?;Email with Attachments
use std::fs;
use base64::Engine;
use laneful_rs::Attachment;
// Read file and encode as base64
let file_data = fs::read("/path/to/document.pdf")?;
let content = base64::engine::general_purpose::STANDARD.encode(&file_data);
let email = Email::builder()
.from("sender@example.com", None)
.to("user@example.com", None)
.subject("Document Attached")
.text_content("Please find the document attached.")
.attachment(Attachment::new("document.pdf", content, "application/pdf"))
.build()?;
let response = client.send_one(email)?;Multiple Recipients with Reply-To
let email = Email::builder()
.from("sender@example.com", Some("Your Name"))
.to("user1@example.com", Some("User One"))
.to("user2@example.com", Some("User Two"))
.cc("cc@example.com", Some("CC Recipient"))
.bcc("bcc@example.com", Some("BCC Recipient"))
.reply_to("reply@example.com", Some("Reply To"))
.subject("Email to Multiple Recipients")
.text_content("This email is being sent to multiple recipients.")
.build()?;
let response = client.send_one(email)?;Scheduled Email
use std::time::{SystemTime, UNIX_EPOCH};
// Schedule for 24 hours from now
let send_time = SystemTime::now()
.duration_since(UNIX_EPOCH)?
.as_secs() + (24 * 60 * 60);
let email = Email::builder()
.from("sender@example.com", None)
.to("user@example.com", None)
.subject("Scheduled Email")
.text_content("This email was scheduled.")
.send_time(send_time)
.build()?;
let response = client.send_one(email)?;Batch Email Sending
let emails = vec![
Email::builder()
.from("sender@example.com", None)
.to("user1@example.com", None)
.subject("Email 1")
.text_content("First email content.")
.build()?,
Email::builder()
.from("sender@example.com", None)
.to("user2@example.com", None)
.subject("Email 2")
.text_content("Second email content.")
.build()?,
];
let response = client.send(emails)?;Message IDs, Headers and Webhook Data
use laneful_rs::MailSettings;
let email = Email::builder()
.from("orders@example.com", None)
.to("customer@example.com", None)
.subject("Your order has shipped")
.text_content("Your order is on its way.")
.header("X-Order-Id", "1042")
.webhook_data("order_id", "1042") // returned as metadata on every webhook event
.build()?;
let response = client.send_one_with_mail_settings(
email,
Some(MailSettings {
return_message_ids: Some(true),
..Default::default()
}),
)?;
// Equal to message_id on this email's webhook events
println!("Message ID: {:?}", response.first_message_id());API Reference
LanefulClient
- •
LanefulClient::new(endpoint, api_key) -> Result<LanefulClient>-endpointis the fullhttps://URL - •
send_one(email: Email) -> Result<SendEmailResponse>- Send one email - •
send(emails: Vec<Email>) -> Result<SendEmailResponse>- Send several emails in one request - •
send_one_with_mail_settings(email, Option<MailSettings>),send_with_mail_settings(emails, Option<MailSettings>)- The same, with mail settings - • With the
asyncfeature:send_one_async,send_async,send_one_with_mail_settings_async,send_with_mail_settings_async, taking the same arguments
Email::builder()
- •
from(email, name: Option<&str>)- Sender (required) - •
from_header(email, name)- Visible From header, if it should differ fromfrom - •
to,cc,bcc(email, name)- Add one recipient per call; at least one and at most 1000 in total - •
reply_to(email, name) - •
subject- Required, also with a template - •
text_content,html_content,template_id,template_data(serde_json::Value)- Content or a template is required - •
attachment(Attachment::new(file_name, base64_content, content_type)) - •
header(name, value)- Custom email header. From, To, Cc, Bcc, Reply-To and Subject come from the builder fields and Laneful generates the Message-ID as<message_id@laneful-host>, so those headers are ignored here (see Sending Email) - •
webhook_data(key, value)- Your own data, up to 20 keys (keys up to 50 bytes, values up to 100 bytes in UTF-8); Laneful returns it unchanged asmetadataon every webhook event for the email - •
send_time(u64)- Unix timestamp in seconds, at most 72 hours ahead - •
tag- Up to 100 bytes in UTF-8 - •
tracking(Tracking)-opens,clicks,unsubscribes(Option<bool>,None= API default, true),unsubscribe_group_id: Option<u64>,unsubscribe_group_name: Option<String> - •
build() -> Result<Email>- Validates the required fields and the recipient,tagandwebhook_datalimits before sending; the API checkssend_time
MailSettings and SendEmailResponse
- •
MailSettings:sandbox_mode(accept the request without sending anything) andreturn_message_ids, bothOption<bool>, andidempotency_key: Option<String>(1 to 36 bytes, 0.3.0 and later; see Errors and Retries below);Noneis omitted. See Mail Settings. - •
SendEmailResponse:status: String,message_ids: Option<Vec<String>>,message_id: Option<String>andfirst_message_id(). Setreturn_message_ids: Some(true)to get message IDs; this requires every email in the request to have exactly one recipient. Each matches themessage_idon that email's webhook events.
Errors and Retries
Methods return laneful_rs::Result<T>; the error type is LanefulError:
- •
ValidationError(String)-build()rejected the email, oridempotency_keyis outside 1 to 36 bytes - •
ConfigError(String)- Empty or invalid endpoint or API key - •
ApiError(String)- The API returned an error status (401 included); carries the API's error message rather than the status code - •
HttpError(reqwest::Error)- The request failed, for example a connection failure or timeout - •
ParseError(serde_json::Error)- Unexpected response body
Retries are up to you: the client sends each request once. From 0.3.0 every request, blocking or async, times out after 30 seconds; in 0.2 only blocking methods do. A request that timed out may already have been accepted, so when you retry a send, reuse the same idempotency key (mail_settings.idempotency_key, see Sending Email). 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).
let response = client.send_one_with_mail_settings(
email,
Some(MailSettings {
idempotency_key: Some(format!("order-{order_id}-receipt")),
..Default::default()
}),
)?;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: u64 as their first argument (the API routes them under /v1/workspaces/{workspace_id}/...).
Webhooks
The SDK verifies webhook signatures and provides a constant for every event name, and serde_json parses the events. This handler uses axum:
Signature Verification & Processing
use axum::{
body::Bytes,
http::{HeaderMap, StatusCode},
};
use laneful_rs::{verify_webhook_signature, WEBHOOK_EVENT_BOUNCE, WEBHOOK_EVENT_DELIVERY};
use serde_json::Value;
// Route: Router::new().route("/webhook", axum::routing::post(laneful_webhook))
async fn laneful_webhook(headers: HeaderMap, body: Bytes) -> StatusCode {
let secret = std::env::var("LANEFUL_WEBHOOK_SECRET").unwrap_or_default();
let signature = headers
.get("x-webhook-signature")
.and_then(|value| value.to_str().ok())
.unwrap_or_default();
// Verify the raw body bytes before parsing them
if secret.is_empty() || !verify_webhook_signature(&secret, &body, signature) {
return StatusCode::UNAUTHORIZED;
}
// Batch mode sends a JSON array of events, single mode one event object
let events = match serde_json::from_slice::<Value>(&body) {
Ok(Value::Array(events)) => events,
Ok(event) => vec![event],
Err(_) => return StatusCode::BAD_REQUEST,
};
for event in &events {
match event["event"].as_str() {
Some(WEBHOOK_EVENT_DELIVERY) => println!("Delivered: {}", event["message_id"]),
Some(WEBHOOK_EVENT_BOUNCE) => {
println!("Bounced: {} (hard: {})", event["email"], event["is_hard"])
}
_ => {} // ignore other event types
}
}
StatusCode::OK
}- •
verify_webhook_signature(secret: &str, payload: &[u8], signature: &str) -> boolcomputes the HMAC-SHA256 of the raw request body, keyed with the webhook secret, and compares it with theX-Webhook-Signatureheader. Pass it the exact bytes you received; re-serialized JSON can differ from the signed bytes. - • Laneful sends the signature as 64 lowercase hex characters with no prefix. From 0.3.0 the helper also accepts a
sha256=-prefixed value and returns false when the secret or signature is empty; 0.2 rejects the prefix. - • In batch mode the body is a JSON array of events; otherwise it is one event object, and the handler above accepts both. Fields are at the top level, and
metadataholds thewebhook_datayou sent with the email. See Webhooks for every field. - • Event name constants:
WEBHOOK_EVENT_REQUEST,WEBHOOK_EVENT_DELIVERY,WEBHOOK_EVENT_OPEN,WEBHOOK_EVENT_CLICK,WEBHOOK_EVENT_DROP,WEBHOOK_EVENT_SPAM_COMPLAINT,WEBHOOK_EVENT_UNSUBSCRIBE,WEBHOOK_EVENT_BOUNCE(request,delivery,open,click,drop,spam_complaint,unsubscribe,bounce).WEBHOOK_EVENT_TYPESlists them andis_valid_webhook_event(&str)checks a name. - • Answer 2xx within 30 seconds. Until you do, Laneful keeps retrying for up to 24 hours, so an event can arrive more than once.
Ready to Get Started?
Start sending emails with Rust in minutes. Check out the examples and integrate with your application.