Documentation

Go SDK

Go 1.23+
Go Modules

Send emails with Go using the official Laneful Go SDK. Built for modern Go applications with comprehensive features and type safety.

Full Feature Support

Templates, attachments, tracking, webhooks

Type Safe

Typed structs & standard Go errors

Modern Go

Go 1.23+ with context support

Prerequisites

To get the most out of this guide, you'll need:

  • • Go 1.23 or higher
  • • Go modules enabled
  • • A Laneful account with API key
  • • Verified domain for sending emails

Installation

Go Modules

Add the SDK to your module:

go get github.com/lanefulhq/laneful-go@v1.2.0

Quick Start

Send your first email in minutes:

Send Simple Text Email

package main

import (
    "context"
    "log"

    "github.com/lanefulhq/laneful-go"
)

func main() {
    // Create client
    client := laneful.NewLanefulClient(
        "https://your-endpoint.z1.send.laneful.net",
        "your-auth-token",
    )

    // Create email
    email := laneful.Email{
        From: laneful.Address{
            Email: "sender@example.com",
            Name:  "Your Name",
        },
        To: []laneful.Address{
            {Email: "recipient@example.com", Name: "Recipient Name"},
        },
        Subject:     "Hello from Laneful!",
        TextContent: "This is a simple test email sent using the Laneful Go SDK.",
    }

    // Send email
    resp, err := client.SendEmail(context.Background(), email)
    if err != nil {
        log.Fatal("Failed to send email:", err)
    }

    log.Printf("✓ Email sent successfully! Status: %s", resp.Status)
}

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

// All three flags are always sent: a flag left out goes as false
// and turns that tracking off
tracking := &laneful.TrackingSettings{
    Opens:        true,
    Clicks:       true,
    Unsubscribes: true,
}

email := laneful.Email{
    From: laneful.Address{
        Email: "sender@example.com",
        Name:  "Your Name",
    },
    To: []laneful.Address{
        {Email: "recipient@example.com", Name: "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",
}

if _, err := client.SendEmail(context.Background(), email); err != nil {
    log.Fatal(err)
}

Template Email

email := laneful.Email{
    From: laneful.Address{Email: "sender@example.com"},
    To:   []laneful.Address{{Email: "user@example.com"}},
    Subject:    "Welcome to Acme",
    TemplateID: "welcome-template",
    TemplateData: map[string]interface{}{
        "name":         "John Doe",
        "company":      "Acme Corporation",
        "activation_link": "https://example.com/activate",
    },
}

if _, err := client.SendEmail(context.Background(), email); err != nil {
    log.Fatal(err)
}

Email with Attachments

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "github.com/lanefulhq/laneful-go"
)

// Read file and encode as base64
fileData, err := os.ReadFile("/path/to/document.pdf")
if err != nil {
    log.Fatal(err)
}

email := laneful.Email{
    From: laneful.Address{Email: "sender@example.com"},
    To:   []laneful.Address{{Email: "user@example.com"}},
    Subject:     "Document Attached",
    TextContent: "Please find the document attached.",
    Attachments: []laneful.Attachment{
        {
            FileName:    "document.pdf",
            Content:     base64.StdEncoding.EncodeToString(fileData),
            ContentType: "application/pdf",
        },
    },
}

if _, err := client.SendEmail(context.Background(), email); err != nil {
    log.Fatal(err)
}

Multiple Recipients with Reply-To

email := laneful.Email{
    From: laneful.Address{
        Email: "sender@example.com",
        Name:  "Your Name",
    },
    To: []laneful.Address{
        {Email: "user1@example.com", Name: "User One"},
        {Email: "user2@example.com", Name: "User Two"},
    },
    CC: []laneful.Address{
        {Email: "cc@example.com", Name: "CC Recipient"},
    },
    BCC: []laneful.Address{
        {Email: "bcc@example.com", Name: "BCC Recipient"},
    },
    ReplyTo: &laneful.Address{
        Email: "reply@example.com",
        Name:  "Reply To",
    },
    Subject:     "Email to Multiple Recipients",
    TextContent: "This email is being sent to multiple recipients.",
}

if _, err := client.SendEmail(context.Background(), email); err != nil {
    log.Fatal(err)
}

Scheduled Email

import (
    "context"
    "log"
    "time"

    "github.com/lanefulhq/laneful-go"
)

// Schedule for 24 hours from now
sendTime := time.Now().Add(24 * time.Hour).Unix()

email := laneful.Email{
    From:      laneful.Address{Email: "sender@example.com"},
    To:        []laneful.Address{{Email: "user@example.com"}},
    Subject:   "Scheduled Email",
    TextContent: "This email was scheduled.",
    SendTime:  sendTime,
}

if _, err := client.SendEmail(context.Background(), email); err != nil {
    log.Fatal(err)
}

Batch Email Sending

emails := []laneful.Email{
    {
        From:        laneful.Address{Email: "sender@example.com"},
        To:          []laneful.Address{{Email: "user1@example.com"}},
        Subject:     "Email 1",
        TextContent: "First email content.",
    },
    {
        From:        laneful.Address{Email: "sender@example.com"},
        To:          []laneful.Address{{Email: "user2@example.com"}},
        Subject:     "Email 2",
        TextContent: "Second email content.",
    },
}

if _, err := client.SendEmails(context.Background(), emails); err != nil {
    log.Fatal(err)
}

Webhook Handler Example

import (
    "bytes"
    "encoding/json"
    "io"
    "log"
    "net/http"
    "os"

    "github.com/lanefulhq/laneful-go"
)

var webhookSecret = os.Getenv("LANEFUL_WEBHOOK_SECRET")

// Complete webhook handler implementation
func handleWebhook(w http.ResponseWriter, r *http.Request) {
    // Read the raw request body: the signature covers these exact bytes
    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Failed to read body", http.StatusBadRequest)
        return
    }

    // Extract signature from headers
    signature := r.Header.Get("x-webhook-signature")
    if signature == "" {
        http.Error(w, "Missing signature", http.StatusUnauthorized)
        return
    }

    // Verify signature before parsing (reject everything if no secret is configured)
    if webhookSecret == "" || !laneful.VerifyWebhookSignature(webhookSecret, string(body), signature) {
        http.Error(w, "Invalid signature", http.StatusUnauthorized)
        return
    }

    // Parse webhook data: a JSON array in batch mode, one event object otherwise
    var events []map[string]any
    if trimmed := bytes.TrimSpace(body); len(trimmed) > 0 && trimmed[0] == '[' {
        err = json.Unmarshal(body, &events)
    } else {
        var event map[string]any
        err = json.Unmarshal(body, &event)
        events = []map[string]any{event}
    }
    if err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }

    // Process events; fields are at the top level of each event
    for _, event := range events {
        eventType, _ := event["event"].(string)
        email, _ := event["email"].(string)
        
        switch eventType {
        case "request":
            log.Printf("Email accepted for: %s", email)
        case "delivery":
            log.Printf("Email delivered to: %s", email)
        case "open":
            log.Printf("Email opened by: %s", email)
        case "click":
            if url, ok := event["url"].(string); ok {
                log.Printf("Link clicked by %s: %s", email, url)
            }
        case "bounce":
            if isHard, ok := event["is_hard"].(bool); ok {
                log.Printf("Email bounced (%s) for: %s", 
                    map[bool]string{true: "hard", false: "soft"}[isHard], email)
            }
        }
    }
    
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Webhook processed successfully"))
}

API Reference

LanefulClient

Constructors

  • • NewLanefulClient(baseURL, authToken string) *LanefulClient - Creates a new client with default timeout (30 seconds)

Methods

  • • SendEmail(ctx context.Context, email Email) (*ApiResponse, error) - Send single email
  • • SendEmails(ctx context.Context, emails []Email) (*ApiResponse, error) - Send multiple emails in one request
  • • SendEmailsWithOptions(ctx context.Context, request *EmailRequest) (*ApiResponse, error) - Send emails with request-level MailSettings

Email Struct

Required Fields

  • • From Address - Sender address
  • • Subject string - Email subject (also required with TemplateID)
  • • At least one recipient in To, CC or BCC, and one of TextContent, HTMLContent or TemplateID. The API validates these and returns an error if any is missing (the SDK leaves validation to the API)

Optional Fields

  • • To []Address - Recipient addresses
  • • CC []Address - CC recipient addresses
  • • BCC []Address - BCC recipient addresses
  • • ReplyTo *Address - Reply-to address
  • • FromHeader Address - Address shown in the From header, if different from From
  • • TextContent string - Plain text content
  • • HTMLContent string - HTML content
  • • TemplateID string - Template ID
  • • TemplateData map[string]interface{} - Template data
  • • Attachments []Attachment - File attachments
  • • SendTime int64 - Scheduled send time (Unix timestamp)
  • • Tracking *TrackingSettings - Email tracking configuration; leave it nil for the API defaults (opens, clicks and unsubscribes all on)
  • • Tag string - Email tag for categorization
  • • Headers map[string]string - Custom headers
  • • WebhookData map[string]string - Custom data (up to 20 keys; keys up to 50 bytes, values up to 100 bytes in UTF-8), returned unchanged as metadata on every webhook event for this email

Utility Structs

  • • Address{Email, Name string} - Email address with optional name
  • • Attachment{FileName, Content, ContentType, InlineID string} - File attachment (Content is Base64; set FileName or InlineID)
  • • TrackingSettings{Opens, Clicks, Unsubscribes bool, UnsubscribeGroupID *int64, UnsubscribeGroupName *string} - Email tracking configuration. Set all three bools explicitly: the SDK always sends them, and a field left out goes as false, turning that tracking off
  • • MailSettings{SandboxMode, ReturnMessageIds bool; IdempotencyKey string} - Request-level settings. SandboxMode: a dry run; nothing is persisted or sent. ReturnMessageIds: get MessageIds in the response (every email must have exactly one recipient). IdempotencyKey: 1 to 36 bytes, see Error Handling (v1.2.0 and later)
  • • EmailRequest{Emails []Email, MailSettings *MailSettings} - Request for SendEmailsWithOptions
  • • ApiResponse{Status string, MessageIds []string} - API response structure. Each ID in MessageIds matches the message_id on that email's webhook events

Webhook Functions

Signature Verification

  • • VerifyWebhookSignature(secret, payload, signature string) bool - Verifies webhook signature using HMAC-SHA256: compares signature with the lowercase hex HMAC of payload, the format Laneful sends. From v1.2.0 a sha256= prefix is also accepted, and an empty secret or signature returns false

Organization API Methods

  • • Unsubscribe groups: ListUnsubscribeGroups(ctx, workspaceID, ...), CreateUnsubscribeGroup(ctx, workspaceID, ...), UpdateUnsubscribeGroup(ctx, workspaceID, unsubscribeGroupID, ...)
  • • Domains: ListDomains(ctx, workspaceID, ...), GetDomain(ctx, workspaceID, domain), CreateDomain(ctx, workspaceID, ...), UpdateDomain(ctx, workspaceID, domain, ...), VerifyDomain(ctx, workspaceID, domain), DeleteDomain(ctx, workspaceID, domain)
  • • Analytics: ListDomainSpamRatioRadar, ListGooglePostmasterSpamReports, ListSndsReports

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 workspaceID int64 as their first argument after ctx (the API routes them under /v1/workspaces/{workspace_id}/...).

Error Handling

Comprehensive error handling with Go's standard error interface:

import (
    "context"
    "log"
    "strings"

    "github.com/lanefulhq/laneful-go"
)

func sendEmailWithErrorHandling(client *laneful.LanefulClient, email laneful.Email) {
    resp, err := client.SendEmail(context.Background(), email)
    if err != nil {
        // The SDK returns plain errors: match on the message
        switch {
        case strings.Contains(err.Error(), "API error"):
            log.Printf("✗ API error: %v", err)
            log.Println("Please check your API credentials and email fields")
        case strings.Contains(err.Error(), "failed to send request"):
            log.Printf("✗ Network error: %v", err)
            log.Println("Please check your network connection and endpoint URL")
        default:
            log.Printf("✗ Unexpected error: %v", err)
        }
        return
    }

    log.Printf("✓ Email sent successfully! Status: %s", resp.Status)
}

Error Types

  • • API errors - API returns error response (any non-200 status, including invalid input, since the API handles all validation)
    Check error message for details
  • • Network errors - HTTP communication fails
    Check connection and endpoint URL
  • • JSON errors - Response parsing fails

Best Practices

  • • Always check errors from API calls
  • • Use context for request cancellation
  • • 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 IdempotencyKey (see below)
  • • Use structured logging for better debugging

Duplicate Send Protection

Set IdempotencyKey (1 to 36 bytes, see Sending Email) and reuse it when you retry a send, for example after a timeout:

resp, err := client.SendEmailsWithOptions(ctx, &laneful.EmailRequest{
    Emails:       []laneful.Email{email},
    MailSettings: &laneful.MailSettings{IdempotencyKey: fmt.Sprintf("order-%d-receipt", orderID)},
})

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 v1.2.0 or later.

Webhook Handling

Secure webhook handling with signature verification. 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 read the body with io.ReadAll and verify it before parsing. Then decode a batch (JSON array) or a single event (JSON object) into your own types, as the examples show; the SDK leaves payload types to you. Event fields are at the top level of each event, and metadata holds the WebhookData you sent with the email; see Webhooks for every field. The examples expect the Laneful payload format (the default).

Basic Signature Verification

import (
    "io"
    "net/http"
    "os"

    "github.com/lanefulhq/laneful-go"
)

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    // Read the raw request body
    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Failed to read body", http.StatusBadRequest)
        return
    }

    // Get signature from headers
    signature := r.Header.Get("x-webhook-signature")
    secret := os.Getenv("LANEFUL_WEBHOOK_SECRET")

    // Verify signature (reject everything if no secret is configured)
    if secret != "" && laneful.VerifyWebhookSignature(secret, string(body), signature) {
        // Parse and process body here (see Advanced Webhook Processing)
        w.WriteHeader(http.StatusOK)
    } else {
        http.Error(w, "Invalid signature", http.StatusUnauthorized)
    }
}

Advanced Webhook Processing

import (
    "bytes"
    "encoding/json"
    "io"
    "log"
    "net/http"
    "os"

    "github.com/lanefulhq/laneful-go"
)

// Fields are at the top level of each event. ID is unique per event and
// unchanged on retries; Metadata is the WebhookData sent with the email.
type WebhookEvent struct {
    ID                 string            `json:"id"`
    Event              string            `json:"event"`
    Email              string            `json:"email"`
    MessageID          string            `json:"message_id"`
    Timestamp          int64             `json:"timestamp"`
    Metadata           map[string]string `json:"metadata"`
    URL                string            `json:"url"`                  // click
    IsHard             bool              `json:"is_hard"`              // bounce
    Reason             string            `json:"reason"`               // drop
    UnsubscribeGroupID int64             `json:"unsubscribe_group_id"` // unsubscribe; 0 = global
}

var webhookSecret = os.Getenv("LANEFUL_WEBHOOK_SECRET")

func advancedWebhookHandler(w http.ResponseWriter, r *http.Request) {
    // Step 1: Read raw payload
    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Failed to read body", http.StatusBadRequest)
        return
    }

    // Step 2: Extract signature
    signature := r.Header.Get("x-webhook-signature")
    if signature == "" {
        http.Error(w, "Missing signature", http.StatusUnauthorized)
        return
    }

    // Step 3: Verify signature (reject everything if no secret is configured)
    if webhookSecret == "" || !laneful.VerifyWebhookSignature(webhookSecret, string(body), signature) {
        http.Error(w, "Invalid signature", http.StatusUnauthorized)
        return
    }

    // Step 4: Parse payload: a JSON array in batch mode, one event object otherwise
    var events []WebhookEvent
    if trimmed := bytes.TrimSpace(body); len(trimmed) > 0 && trimmed[0] == '[' {
        err = json.Unmarshal(body, &events)
    } else {
        var event WebhookEvent
        err = json.Unmarshal(body, &event)
        events = []WebhookEvent{event}
    }
    if err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }

    // Step 5: Process events
    for _, event := range events {
        switch event.Event {
        case "request":
            log.Printf("Email %s accepted for %s", event.MessageID, event.Email)
        case "delivery":
            log.Printf("Email %s delivered to %s (metadata: %v)", event.MessageID, event.Email, event.Metadata)
        case "open":
            log.Printf("Email %s opened by %s", event.MessageID, event.Email)
        case "click":
            log.Printf("Link clicked by %s: %s", event.Email, event.URL)
        case "bounce":
            log.Printf("Email to %s bounced (hard: %t)", event.Email, event.IsHard)
        case "drop":
            log.Printf("Email to %s dropped: %s", event.Email, event.Reason)
        case "spam_complaint":
            log.Printf("Spam complaint from %s", event.Email)
        case "unsubscribe":
            log.Printf("Unsubscribe from %s (group %d)", event.Email, event.UnsubscribeGroupID)
        }
    }

    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Webhook processed successfully"))
}

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
  • • Constant-time comparison (timing attack protection)
  • • Bare hex signatures, as Laneful sends them (v1.2.0 and later also accept a sha256= prefix)

Integration

  • • Works with any HTTP framework
  • • Easy error handling with Go idioms

Ready to Get Started?

Start sending emails with Go in minutes. Check out the examples and integrate with your application.