C# SDK
Send emails with C# using the official Laneful C# SDK. Built for modern .NET applications with comprehensive features and type safety.
Templates, attachments, tracking, webhooks
Built-in validation & error handling
.NET 9.0+ with async/await
On this page
Prerequisites
To get the most out of this guide, you'll need:
- • .NET 9.0 or higher
- • A Laneful account with API key
- • Verified domain for sending emails
Installation
NuGet Package
Install the package using the .NET CLI:
dotnet add package Laneful.CSharp
This page describes version 1.3.0. Use 1.2.0 or later for webhooks: earlier versions reject payloads that contain a request event. Version 1.3.0 adds the idempotency key, keeps every webhook field and event type, accepts the empty lane_id on request events, and fixes sends to addresses without a name, which the API rejected in 1.2.0.
Quick Start
Send your first email in minutes:
Send Simple Text Email
using Laneful;
using Laneful.Models;
using Laneful.Exceptions;
// Create client
var client = new LanefulClient(
"https://your-endpoint.z1.send.laneful.net",
"your-auth-token"
);
// Create email
var email = new Email.Builder()
.From(new Address("sender@example.com", "Your Name"))
.To(new Address("recipient@example.com", "Recipient Name"))
.Subject("Hello from Laneful!")
.TextContent("This is a simple test email sent using the Laneful C# SDK.")
.Build();
// Send email
try
{
var response = await client.SendEmailAsync(email);
Console.WriteLine("✓ Email sent successfully!");
Console.WriteLine($"Response: {string.Join(", ", response)}");
}
catch (ValidationException ex)
{
Console.WriteLine($"✗ Validation error: {ex.Message}");
}
catch (ApiException ex)
{
Console.WriteLine($"✗ API error: {ex.Message}");
Console.WriteLine($"Status code: {ex.StatusCode}");
}
catch (HttpException ex)
{
Console.WriteLine($"✗ HTTP error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"✗ Unexpected error: {ex.Message}");
}Replace https://your-endpoint.z1.send.laneful.net with your organization's own HTTP API endpoint and your-auth-token with an API key, both available in the dashboard under Workspaces → Workspace Settings → API Keys (see Sending Email). The API is HTTPS-only.
Examples
Common use cases and patterns:
HTML Email with Tracking
// Create tracking settings
var tracking = new TrackingSettings(opens: true, clicks: true, unsubscribes: true);
var email = new Email.Builder()
.From(new Address("sender@example.com", "Your Name"))
.To(new Address("recipient@example.com", "Recipient Name"))
.Subject("HTML Email with Tracking")
.HtmlContent("<h1>Welcome!</h1><p>This is an <strong>HTML email</strong> with tracking enabled.</p>")
.TextContent("Welcome! This is an HTML email with tracking enabled.")
.Tracking(tracking)
.Tag("welcome-email")
.Build();
var response = await client.SendEmailAsync(email);Template Email
var email = new Email.Builder()
.From(new Address("sender@example.com"))
.To(new Address("user@example.com"))
.Subject("Welcome to Acme")
.TemplateId("welcome-template")
.TemplateData(new Dictionary<string, object>
{
["name"] = "John Doe",
["company"] = "Acme Corporation",
["activation_link"] = "https://example.com/activate"
})
.Build();
var response = await client.SendEmailAsync(email);Email with Attachments
// Create attachment from file
var attachment = Attachment.FromFile("/path/to/document.pdf");
var email = new Email.Builder()
.From(new Address("sender@example.com"))
.To(new Address("user@example.com"))
.Subject("Document Attached")
.TextContent("Please find the document attached.")
.Attachment(attachment)
.Build();
var response = await client.SendEmailAsync(email);Multiple Recipients with Reply-To
var email = new Email.Builder()
.From(new Address("sender@example.com", "Your Name"))
.To(new Address("user1@example.com", "User One"))
.To(new Address("user2@example.com", "User Two"))
.Cc(new Address("cc@example.com", "CC Recipient"))
.Bcc(new Address("bcc@example.com", "BCC Recipient"))
.ReplyTo(new Address("reply@example.com", "Reply To"))
.Subject("Email to Multiple Recipients")
.TextContent("This email is being sent to multiple recipients.")
.Build();
var response = await client.SendEmailAsync(email);Scheduled Email
// Schedule for 24 hours from now
var sendTime = DateTimeOffset.UtcNow.AddHours(24).ToUnixTimeSeconds();
var email = new Email.Builder()
.From(new Address("sender@example.com"))
.To(new Address("user@example.com"))
.Subject("Scheduled Email")
.TextContent("This email was scheduled.")
.SendTime(sendTime)
.Build();
var response = await client.SendEmailAsync(email);Batch Email Sending
var emails = new[]
{
new Email.Builder()
.From(new Address("sender@example.com"))
.To(new Address("user1@example.com"))
.Subject("Email 1")
.TextContent("First email content.")
.Build(),
new Email.Builder()
.From(new Address("sender@example.com"))
.To(new Address("user2@example.com"))
.Subject("Email 2")
.TextContent("Second email content.")
.Build()
};
var response = await client.SendEmailsAsync(emails);Webhook Handler Example
using Microsoft.AspNetCore.Mvc;
using Laneful.Webhooks;
[ApiController]
[Route("api/[controller]")]
public class WebhookController : ControllerBase
{
private readonly string _webhookSecret;
private readonly ILogger<WebhookController> _logger;
public WebhookController(ILogger<WebhookController> logger)
{
_logger = logger;
_webhookSecret = Environment.GetEnvironmentVariable("LANEFUL_WEBHOOK_SECRET")
?? throw new InvalidOperationException("LANEFUL_WEBHOOK_SECRET is required");
}
[HttpPost("laneful")]
public async Task<IActionResult> HandleWebhook()
{
try
{
// Read raw payload
using var reader = new StreamReader(Request.Body);
var payload = await reader.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(payload))
{
return BadRequest(new { error = "Empty payload received" });
}
// Convert headers to dictionary
var headers = Request.Headers.ToDictionary(
h => h.Key,
h => h.Value.ToString(),
StringComparer.OrdinalIgnoreCase
);
// Extract signature from headers
var signature = WebhookVerifier.ExtractSignatureFromHeaders(headers);
if (string.IsNullOrEmpty(signature))
{
return Unauthorized(new { error = "Missing signature" });
}
// Verify signature
if (!WebhookVerifier.VerifySignature(_webhookSecret, payload, signature))
{
return Unauthorized(new { error = "Invalid signature" });
}
// Parse and validate payload
var webhookData = WebhookVerifier.ParseWebhookPayload(payload);
// Process events
foreach (var eventData in webhookData.Events)
{
var eventType = eventData["event"]?.ToString();
var email = eventData["email"]?.ToString();
switch (eventType)
{
case "request":
_logger.LogInformation("Email accepted for: {Email}", email);
break;
case "delivery":
_logger.LogInformation("Email delivered to: {Email}", email);
break;
case "open":
_logger.LogInformation("Email opened by: {Email}", email);
break;
case "click":
var url = eventData.GetValueOrDefault("url")?.ToString() ?? "Unknown URL";
_logger.LogInformation("Link clicked by {Email}: {Url}", email, url);
break;
case "bounce":
var isHard = eventData.GetValueOrDefault("is_hard") as bool? ?? false;
_logger.LogInformation("Email bounced ({Type}) for: {Email}",
isHard ? "hard" : "soft", email);
break;
}
}
return Ok(new
{
status = "success",
processed = webhookData.Events.Count,
mode = webhookData.IsBatch ? "batch" : "single"
});
}
catch (ArgumentException ex)
{
return BadRequest(new { error = $"Invalid payload: {ex.Message}" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing webhook");
return StatusCode(500, new { error = "Processing error" });
}
}
}API Reference
LanefulClient
Constructors
- •
LanefulClient(string baseUrl, string authToken, HttpClient? httpClient = null, ILogger<LanefulClient>? logger = null)- Default timeout (30 seconds), optional custom HTTP client and logger - •
LanefulClient(string baseUrl, string authToken, TimeSpan timeout, HttpClient? httpClient = null, ILogger<LanefulClient>? logger = null)- Custom timeout
Pass a logger by name: new LanefulClient(baseUrl, authToken, logger: logger). Every constructor validates its arguments up front and throws ValidationException if the URL or token is empty.
Methods
- •
Task<Dictionary<string, object>> SendEmailAsync(Email email, MailSettings? settings = null)- Send single email - •
Task<Dictionary<string, object>> SendEmailsAsync(IEnumerable<Email> emails, MailSettings? settings = null)- Send multiple emails in one request
Each send method returns the parsed API response (values are JsonElement): status, plus message_ids when ReturnMessageIds is set.
Email.Builder
Required Fields
- •
From(Address from)- Sender address.Build()checks for it and throwsArgumentNullExceptionif it's missing - •
Subject(string subject)- Email subject. Always set it, also for template emails: the API requires a subject, andBuild()leaves that check to the API (if you leave it out, the SDK sends an empty subject) - • At least one recipient (
To,CcorBcc) and content (TextContent,HtmlContentorTemplateId).Build()checks both for you and throwsValidationExceptionif either is missing
Optional Fields
- •
To(Address to)/To(string email, string? name)- Recipient addresses - •
Cc(Address cc)/Cc(string email, string? name)- CC addresses - •
Bcc(Address bcc)/Bcc(string email, string? name)- BCC addresses - •
ReplyTo(Address? replyTo)/ReplyTo(string email, string? name)- Reply-to address - •
FromHeader(Address? fromHeader)/FromHeader(string email, string? name)- Address for the visible From header, if it should differ fromFrom - •
TextContent(string? textContent)- Plain text content - •
HtmlContent(string? htmlContent)- HTML content - •
TemplateId(string? templateId)- Template ID - •
TemplateData(Dictionary<string, object>? templateData)- Template data - •
Attachment(Attachment attachment)- File attachments - •
Headers(Dictionary<string, string>? headers)- Custom headers. Set From, To, Cc, Bcc, Reply-To and Subject with the builder methods and let Laneful generate the Message-ID; header entries for these are ignored (see Sending Email) - •
SendTime(long? sendTime)- Schedule the send up to 72 hours ahead (Unix timestamp in seconds, in the future) - •
WebhookData(Dictionary<string, string>? webhookData)- Your own data, returned unchanged asmetadataon every webhook event for this email: up to 20 keys (up to 50 bytes in UTF-8) with string values (up to 100 bytes) - •
Tag(string? tag)- Email tag for categorization - •
Tracking(TrackingSettings? tracking)- Tracking settings
Field details: Sending Email.
Utility Classes
- •
Address(string email, string? name = null)- Email address with optional name. Validates the address on creation and throwsValidationExceptionif it's empty or malformed - •
Attachment.FromFile(string filePath)- Create attachment from file - •
Attachment(string filename, string contentType, string content, string? inlineId = null)- Create attachment from data:contentis the Base64-encoded file,inlineIdis for inline images - •
TrackingSettings(bool opens = false, bool clicks = false, bool unsubscribes = false, long? unsubscribeGroupId = null, string? unsubscribeGroupName = null)- Email tracking configuration. Tracking is on by default: withoutTracking(...), the API tracks opens, clicks and unsubscribes. When you pass settings, set all three flags: each defaults to false and is always sent, so a flag you leave out turns that tracking off - •
MailSettings(bool? sandboxMode = null, bool? returnMessageIds = null)withstring? IdempotencyKey { get; init; }- Request-level settings for the send methods; pass null to leave a setting out.returnMessageIdsaddsmessage_idsto the response, one per email, each matching themessage_idon that email's webhook events (every email must then have exactly one recipient).sandboxModeaccepts the request without sending it, a safe way to check that your client can reach the API.IdempotencyKey(1 to 36 bytes, 1.3.0 and later) prevents duplicate sends, see Error Handling
WebhookVerifier
Signature Verification
- •
bool VerifySignature(string secret, string payload, string signature)- Verifies theX-Webhook-Signaturevalue (bare hex, as Laneful sends it, or with asha256=prefix) against the raw request body. Returns false for an empty signature and throwsArgumentExceptionif the secret is empty - •
string GenerateSignature(string secret, string payload, bool includePrefix = false)- Generates signature for payload, optionally with thesha256=prefix
Payload Processing
- •
WebhookData ParseWebhookPayload(string payload)- Parse and validate webhook payload structure. ThrowsArgumentExceptionfor invalid JSON or a missing or malformed required field. From 1.3.0, events of unknown types are kept; earlier versions reject the whole payload - •
string GetSignatureHeaderName()- Get the correct header name for webhook signatures - •
string? ExtractSignatureFromHeaders(IDictionary<string, string> headers)- Extract signature from HTTP headers. Build the dictionary withStringComparer.OrdinalIgnoreCaseso any header casing matches: the method looks upx-webhook-signature,X_WEBHOOK_SIGNATUREandHTTP_X_WEBHOOK_SIGNATUREwith the dictionary's comparer
WebhookData
- •
bool IsBatch- Returns true if the payload is a JSON array (batch mode), even with a single event - •
IReadOnlyList<Dictionary<string, object?>> Events- Returns list of parsed events
Each event dictionary holds every field Laneful sends: id, event, email, message_id, lane_id (empty on request events), tag, timestamp, metadata (the WebhookData sent with the email) and the event-specific fields such as url, is_hard, classification and mx_host. Read optional fields with GetValueOrDefault, since each is present only when the event includes it. Use id to skip events you have already processed. Before 1.3.0 the dictionary held only a fixed subset, without id or mx_host. All fields: Webhooks.
Organization API Methods
- • Unsubscribe groups:
ListUnsubscribeGroupsAsync(long workspaceId, ...),CreateUnsubscribeGroupAsync(long workspaceId, ...),UpdateUnsubscribeGroupAsync(long workspaceId, long unsubscribeGroupId, ...) - • Domains:
ListDomainsAsync(long workspaceId, ...),GetDomainAsync(long workspaceId, string domain),CreateDomainAsync(long workspaceId, ...),UpdateDomainAsync(long workspaceId, string domain, ...),VerifyDomainAsync(long workspaceId, string domain),DeleteDomainAsync(long workspaceId, string domain) - • Analytics:
ListDomainSpamRatioRadarAsync,ListGooglePostmasterSpamReportsAsync,ListSndsReportsAsync
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 long workspaceId as their first argument (the API routes them under /v1/workspaces/{workspace_id}/...).
Error Handling
Comprehensive error handling with specific exception types:
try
{
var response = await client.SendEmailAsync(email);
Console.WriteLine("✓ Email sent successfully!");
Console.WriteLine($"Response: {string.Join(", ", response)}");
}
catch (ValidationException ex)
{
// Invalid input data
Console.WriteLine($"✗ Validation error: {ex.Message}");
Console.WriteLine("Please check your email configuration");
}
catch (ApiException ex)
{
// API returned an error
Console.WriteLine($"✗ API error: {ex.Message}");
Console.WriteLine($" Status code: {ex.StatusCode}");
Console.WriteLine($" Error message: {ex.ErrorMessage}");
Console.WriteLine("Please check your API credentials and endpoint");
}
catch (HttpException ex)
{
// Network or HTTP-level error
Console.WriteLine($"✗ HTTP error: {ex.Message}");
Console.WriteLine($" Status code: {ex.StatusCode}");
Console.WriteLine("Please check your network connection and endpoint URL");
}
catch (Exception ex)
{
// Other unexpected errors
Console.WriteLine($"✗ Unexpected error: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}Exception Types
- •
ValidationException- Input validation fails - •
ApiException- API returns error response
Properties: StatusCode, ErrorMessage - •
HttpException- HTTP communication fails (StatusCode0 for network errors), the endpoint returns 404, or the response isn't JSON
Properties: StatusCode - •
TaskCanceledException- The request timed out. It arrives as is, outside the Laneful exception types, so catch it separately - •
LanefulException- Base exception class
Best Practices
- • Always wrap API calls in try-catch
- • Handle specific exception types first
- • Log errors with context information
- • The SDK leaves retries to you. A send that timed out may already have been accepted, so when you retry it, reuse the same
IdempotencyKey(see below)
Duplicate Send Protection
Set an IdempotencyKey (1 to 36 bytes, see Sending Email) and reuse it when you retry a send, for example after a timeout:
var response = await client.SendEmailAsync(
email,
new MailSettings { IdempotencyKey = $"order-{orderId}-receipt" }
);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. A key outside 1 to 36 bytes throws ValidationException. Requires 1.3.0 or later.
Webhook Handling
Comprehensive webhook handling with signature verification, payload parsing, and validation:
- • Pass
VerifySignaturethe body exactly as received, before parsing it. Laneful signs that raw body with HMAC-SHA256, keyed with your webhook secret, and sends the lowercase hex digest, with no prefix, inX-Webhook-Signature, so re-serialized JSON won't match.VerifySignaturealso accepts asha256=prefix. - • Return a 2xx within 30 seconds to acknowledge each webhook call; Laneful automatically retries any other outcome for up to 24 hours. Reserve 401 for an invalid signature and 400 for a payload that fails to parse, and answer 5xx if your handler fails.
- • Use the default Laneful webhook format with
ParseWebhookPayload; it reads that format rather than the Mailgun or SendGrid formats.
Basic Signature Verification
using Laneful.Webhooks;
// In your controller action
using var reader = new StreamReader(Request.Body);
var payload = await reader.ReadToEndAsync(); // Get the raw request body
var signature = Request.Headers["X-Webhook-Signature"].ToString();
var secret = "your-webhook-secret";
if (!WebhookVerifier.VerifySignature(secret, payload, signature))
{
// Invalid signature
return Unauthorized();
}
try
{
// Process webhook data
var webhookData = WebhookVerifier.ParseWebhookPayload(payload);
// Handle webhook events
}
catch (ArgumentException)
{
// Not a valid Laneful payload
return BadRequest();
}
return Ok();Advanced Webhook Processing
using Laneful.Webhooks;
using Microsoft.AspNetCore.Mvc;
// Complete webhook verification and processing workflow
[ApiController]
[Route("webhooks/laneful")]
public class LanefulWebhookController : ControllerBase
{
private readonly string _webhookSecret =
Environment.GetEnvironmentVariable("LANEFUL_WEBHOOK_SECRET")
?? throw new InvalidOperationException("LANEFUL_WEBHOOK_SECRET is required");
[HttpPost]
public async Task<IActionResult> Receive()
{
// Step 1: Get raw payload
using var reader = new StreamReader(Request.Body);
var payload = await reader.ReadToEndAsync();
// Step 2: Extract signature from headers (supports multiple formats)
var headers = Request.Headers.ToDictionary(
h => h.Key,
h => h.Value.ToString(),
StringComparer.OrdinalIgnoreCase
);
var signature = WebhookVerifier.ExtractSignatureFromHeaders(headers);
// Step 3: Verify signature
if (string.IsNullOrEmpty(signature) ||
!WebhookVerifier.VerifySignature(_webhookSecret, payload, signature))
{
return Unauthorized(new { error = "Invalid webhook signature" });
}
// Step 4: Parse and validate payload structure
WebhookData webhookData;
try
{
webhookData = WebhookVerifier.ParseWebhookPayload(payload);
}
catch (ArgumentException ex)
{
return BadRequest(new { error = $"Invalid payload: {ex.Message}" });
}
// Step 5: Process events (handles both batch and single event formats).
// An exception thrown here makes ASP.NET Core answer 500, so Laneful retries the request.
foreach (var eventData in webhookData.Events)
{
var eventType = eventData["event"]?.ToString();
switch (eventType)
{
case "request":
HandleRequestEvent(eventData);
break;
case "delivery":
HandleDeliveryEvent(eventData);
break;
case "open":
HandleOpenEvent(eventData);
break;
case "click":
HandleClickEvent(eventData);
break;
case "bounce":
HandleBounceEvent(eventData);
break;
case "drop":
HandleDropEvent(eventData);
break;
case "spam_complaint":
HandleSpamComplaintEvent(eventData);
break;
case "unsubscribe":
HandleUnsubscribeEvent(eventData);
break;
}
}
return Ok();
}
// Your event handlers
private void HandleRequestEvent(Dictionary<string, object?> eventData) { }
private void HandleDeliveryEvent(Dictionary<string, object?> eventData) { }
private void HandleOpenEvent(Dictionary<string, object?> eventData) { }
private void HandleClickEvent(Dictionary<string, object?> eventData) { }
private void HandleBounceEvent(Dictionary<string, object?> eventData) { }
private void HandleDropEvent(Dictionary<string, object?> eventData) { }
private void HandleSpamComplaintEvent(Dictionary<string, object?> eventData) { }
private void HandleUnsubscribeEvent(Dictionary<string, object?> eventData) { }
}Batch Mode Support
using Laneful.Webhooks;
// payload: the verified raw request body
void ProcessWebhook(string payload)
{
var webhookData = WebhookVerifier.ParseWebhookPayload(payload);
if (webhookData.IsBatch)
{
// Processing multiple events in batch mode
Console.WriteLine($"Processing {webhookData.Events.Count} events in batch");
}
else
{
// Processing single event
Console.WriteLine("Processing single event");
}
// Process all events
foreach (var eventData in webhookData.Events)
{
Console.WriteLine($"{eventData["event"]}: {eventData["email"]}");
}
}Supported Webhook Events
Delivery Events
- •
request- Email accepted and queued for delivery - •
delivery- Email delivered successfully - •
bounce- Email bounced (hard or soft) - •
drop- Email dropped (spam, invalid, etc.) - •
spam_complaint- Recipient marked email as spam
Engagement Events
- •
open- Email opened by recipient - •
click- Link clicked in email - •
unsubscribe- Recipient unsubscribed
Use version 1.2.0 or later: it supports every event type listed here, including request (earlier versions reject payloads that contain one). From 1.3.0, ParseWebhookPayload also keeps events of types not listed here; 1.2.0 rejects the whole payload, every event of a batch included, if any event has such a type. Temporary delivery failures arrive as a bounce with is_hard: false rather than as a separate deferral event.
Webhook Features
Security
- • HMAC-SHA256 signature verification
- • Bare hex signatures, as Laneful sends them (a
sha256=prefix is also accepted) - • Constant-time comparison (timing attack protection)
- • Multiple header format support
Validation
- • JSON payload structure validation
- • Required field validation
- • Email format validation
- • Numeric timestamp validation
Ready to Get Started?
Start sending emails with C# in minutes. Check out the examples and integrate with your application.