Documentation

Everything you need to integrate SparkMailr into your application

Quick Start API Reference

Quick Start Guide

Get started with SparkMailr in less than 5 minutes. Choose your preferred programming language and follow the integration guide.

Python

pip install sparkmailr

Node.js

npm install @sparkmailr/nodejs-sdk

PHP

composer require sparkmailr/php-sdk

Go

go get github.com/sparkmailr/go-sdk

Ruby

gem install sparkmailr

Java

implementation 'com.sparkmailr:sparkmailr-java-sdk:1.0.0'

C# .NET

dotnet add package SparkMailr.SDK

Authentication

SparkMailr uses API keys for authentication. You can generate an API key from your dashboard.

POST /api/v1/emails/send

Headers: Authorization: Bearer YOUR_API_KEY

# Example with curl
curl -X POST https://api.sparkmailr.com/v1/emails/send \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": ["user@example.com"],
    "from": "noreply@yourapp.com",
    "subject": "Welcome!",
    "html": "

Hello World

" }'

Rate Limits

SparkMailr implements rate limiting to ensure fair usage and system stability. Rate limits vary by plan and endpoint.

Rate Limit Headers

Every API response includes rate limit information in headers:

HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200
X-RateLimit-Retry-After: 60

Plan Limits

Plan Requests/Minute Emails/Hour Emails/Month
Free 10 100 1,000
Starter 50 500 10,000
Growth 75 1,250 25,000
Professional 100 2,500 50,000
Business 200 5,000 100,000
Enterprise 500+ Unlimited 500,000+

Handling Rate Limits

# Python example with rate limit handling
import time
import sparkmailr

client = sparkmailr.SparkMailrClient(api_key="your-api-key")

def send_with_retry(email_data, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = client.emails.send(email_data)
            return response
        except sparkmailr.RateLimitError as e:
            if attempt == max_retries - 1:
                raise

            # Wait for reset time or implement exponential backoff
            wait_time = e.retry_after or (2 ** attempt)
            print(f"Rate limited. Waiting {wait_time} seconds...")
            time.sleep(wait_time)

# Usage
try:
    response = send_with_retry({
        "to": ["user@example.com"],
        "from": "noreply@yourapp.com",
        "subject": "Test Email",
        "html": "<h1>Hello World</h1>"
    })
    print(f"Email sent: {response.id}")
except Exception as e:
    print(f"Failed to send email: {e}")

Error Handling

SparkMailr returns standard HTTP status codes and detailed error messages to help you handle issues gracefully.

HTTP Status Codes

Status Code Description Retry
200 Success N/A
400 Bad Request - Invalid parameters No
401 Unauthorized - Invalid API key No
403 Forbidden - Insufficient permissions No
429 Too Many Requests - Rate limited Yes
500 Internal Server Error Yes

Error Response Format

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid email address format",
    "details": {
      "field": "to",
      "value": "invalid-email",
      "suggestion": "Please provide a valid email address"
    }
  },
  "request_id": "req_1234567890",
  "timestamp": "2025-01-15T10:30:00Z"
}

SDK Error Handling

# Python SDK error handling
import sparkmailr

client = sparkmailr.SparkMailrClient(api_key="your-api-key")

try:
    response = client.emails.send({
        "to": ["user@example.com"],
        "from": "noreply@yourapp.com",
        "subject": "Test Email",
        "html": "<h1>Hello World</h1>"
    })
    print(f"Success: {response.id}")

except sparkmailr.AuthenticationError as e:
    print(f"Authentication failed: {e.message}")
    # Check your API key

except sparkmailr.ValidationError as e:
    print(f"Validation error: {e.message}")
    print(f"Field: {e.details.get('field')}")
    # Fix the validation issue

except sparkmailr.RateLimitError as e:
    print(f"Rate limited: {e.message}")
    print(f"Retry after: {e.retry_after} seconds")
    # Implement backoff logic

except sparkmailr.SparkMailrError as e:
    print(f"API error: {e.message}")
    # Handle other API errors

⚠️ Important

Always implement proper error handling in production. Log errors for debugging but never expose sensitive information to end users.

Python SDK

The SparkMailr Python SDK provides a simple and intuitive interface for sending emails.

Installation

pip install sparkmailr

Basic Usage

import sparkmailr

# Initialize the client
client = sparkmailr.SparkMailrClient(api_key="your-api-key")

# Send a simple email
response = client.emails.send({
    "to": ["user@example.com"],
    "from": "noreply@yourapp.com", 
    "subject": "Welcome to SparkMailr!",
    "html": "<h1>Hello World</h1>",
    "text": "Hello World"
})

print(f"Email sent successfully! ID: {response.id}")

Advanced Features

# Send email with template
response = client.emails.send({
    "to": ["user@example.com"],
    "from": "noreply@yourapp.com",
    "template_id": "welcome-template",
    "template_data": {
        "name": "John Doe",
        "activation_link": "https://app.example.com/activate"
    }
})

# Track email status
status = client.emails.get_status(response.id)
print(f"Email status: {status.status}")

# Get analytics
analytics = client.analytics.get_email_stats(
    start_date="2025-01-01",
    end_date="2025-01-31"
)
print(f"Total sent: {analytics.sent}")
print(f"Delivery rate: {analytics.delivery_rate}%")

Node.js/TypeScript SDK

Full TypeScript support with comprehensive type definitions and modern async/await syntax.

Installation

npm install @sparkmailr/nodejs-sdk
# or
yarn add @sparkmailr/nodejs-sdk

Basic Usage

import { SparkMailrClient } from '@sparkmailr/nodejs-sdk';

// Initialize client
const client = new SparkMailrClient({
    apiKey: 'your-api-key',
    timeout: 30000 // optional
});

// Send email
try {
    const response = await client.emails.send({
        to: ['user@example.com'],
        from: 'noreply@yourapp.com',
        subject: 'Welcome to SparkMailr!',
        html: '<h1>Hello World</h1>',
        text: 'Hello World'
    });

} catch (error) {
    console.error('Email failed:', error.message);
}

Advanced Features

// Send with template
const templateResponse = await client.emails.send({
    to: ['user@example.com'],
    from: 'noreply@yourapp.com',
    templateId: 'welcome-template',
    templateData: {
        name: 'John Doe',
        activationLink: 'https://app.example.com/activate'
    }
});

// Get email status
const status = await client.emails.getStatus(templateResponse.id);

// Bulk email sending
const bulkEmails = [
    { to: 'user1@example.com', subject: 'Welcome User 1' },
    { to: 'user2@example.com', subject: 'Welcome User 2' }
];

const bulkResponse = await client.emails.sendBulk({
    from: 'noreply@yourapp.com',
    html: '<h1>Welcome!</h1>',
    emails: bulkEmails
});

// Analytics
const analytics = await client.analytics.getEmailStats({
    startDate: '2025-01-01',
    endDate: '2025-01-31'
});

PHP SDK

Modern PHP SDK with PSR-4 autoloading, Composer support, and Laravel/Symfony integration.

Installation

composer require sparkmailr/php-sdk

Basic Usage

<?php
require_once 'vendor/autoload.php';

use SparkMailr\SparkMailrClient;
use SparkMailr\Exceptions\SparkMailrException;

// Initialize client
$client = new SparkMailrClient([
    'api_key' => 'your-api-key',
    'timeout' => 30
]);

try {
    // Send email
    $response = $client->emails->send([
        'to' => ['user@example.com'],
        'from' => 'noreply@yourapp.com',
        'subject' => 'Welcome to SparkMailr!',
        'html' => '<h1>Hello World</h1>',
        'text' => 'Hello World'
    ]);
    
    echo "Email sent: " . $response['id'];
} catch (SparkMailrException $e) {
    echo "Error: " . $e->getMessage();
}

Laravel Integration

// Add to config/services.php
'sparkmailr' => [
    'api_key' => env('SPARKMAILR_API_KEY'),
    'base_url' => env('SPARKMAILR_BASE_URL', 'https://api.sparkmailr.com'),
],

// Service Provider
use SparkMailr\SparkMailrClient;

$client = new SparkMailrClient(config('services.sparkmailr'));

// In your controller
public function sendWelcomeEmail(Request $request) 
{
    $response = app(SparkMailrClient::class)->emails->send([
        'to' => [$request->user()->email],
        'from' => 'noreply@yourapp.com',
        'template_id' => 'welcome-template',
        'template_data' => [
            'name' => $request->user()->name,
            'activation_url' => route('activate', $request->user()->id)
        ]
    ]);
    
    return response()->json(['email_id' => $response['id']]);
}

Ruby SDK

Elegant Ruby SDK with Rails integration, RSpec testing, and idiomatic Ruby patterns.

Installation

# Gemfile
gem 'sparkmailr'

# Or install directly
gem install sparkmailr

Basic Usage

require 'sparkmailr'

# Initialize client
client = SparkMailr::Client.new(
  api_key: 'your-api-key',
  timeout: 30
)

begin
  # Send email
  response = client.emails.send(
    to: ['user@example.com'],
    from: 'noreply@yourapp.com',
    subject: 'Welcome to SparkMailr!',
    html: '<h1>Hello World</h1>',
    text: 'Hello World'
  )
  
  puts "Email sent: #{response.id}"
rescue SparkMailr::Error => e
  puts "Error: #{e.message}"
end

Rails Integration

# config/initializers/sparkmailr.rb
SparkMailr.configure do |config|
  config.api_key = Rails.application.credentials.sparkmailr_api_key
  config.base_url = 'https://api.sparkmailr.com'
  config.timeout = 30
end

# In your mailer or controller
class UserMailer < ApplicationMailer
  def welcome_email(user)
    sparkmailr_client = SparkMailr::Client.new
    
    response = sparkmailr_client.emails.send(
      to: [user.email],
      from: 'noreply@yourapp.com',
      template_id: 'welcome-template',
      template_data: {
        name: user.name,
        activation_url: activate_user_url(user)
      }
    )
    
    Rails.logger.info "Welcome email sent: #{response.id}"
  end
end

# Background job with Sidekiq
class SendEmailJob < ApplicationJob
  queue_as :emails
  
  def perform(user_id, template_id, template_data = {})
    user = User.find(user_id)
    client = SparkMailr::Client.new
    
    client.emails.send(
      to: [user.email],
      from: 'noreply@yourapp.com',
      template_id: template_id,
      template_data: template_data
    )
  end
end

Java SDK

Enterprise Java SDK with Maven/Gradle support, Spring Boot integration, and Android compatibility.

Maven Installation

<dependency>
    <groupId>com.sparkmailr</groupId>
    <artifactId>sparkmailr-java-sdk</artifactId>
    <version>1.0.0</version>
</dependency>

Gradle Installation

implementation 'com.sparkmailr:sparkmailr-java-sdk:1.0.0'

Basic Usage

import com.sparkmailr.SparkMailrClient;
import com.sparkmailr.model.SendEmailRequest;
import com.sparkmailr.model.EmailResponse;
import com.sparkmailr.exceptions.SparkMailrException;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class EmailExample {
    public static void main(String[] args) {
        // Initialize client
        SparkMailrClient client = new SparkMailrClient.Builder()
            .apiKey("your-api-key")
            .timeout(30000)
            .build();
        
        try {
            // Send email
            SendEmailRequest request = new SendEmailRequest.Builder()
                .to(Arrays.asList("user@example.com"))
                .from("noreply@yourapp.com")
                .subject("Welcome to SparkMailr!")
                .html("<h1>Hello World</h1>")
                .text("Hello World")
                .build();
            
            EmailResponse response = client.emails().send(request);
            System.out.println("Email sent: " + response.getId());
            
        } catch (SparkMailrException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Spring Boot Integration

// application.yml
sparkmailr:
  api-key: ${SPARKMAILR_API_KEY}
  base-url: https://api.sparkmailr.com
  timeout: 30000

// Configuration
@Configuration
@ConfigurationProperties(prefix = "sparkmailr")
public class SparkMailrConfig {
    private String apiKey;
    private String baseUrl;
    private int timeout;
    
    @Bean
    public SparkMailrClient sparkMailrClient() {
        return new SparkMailrClient.Builder()
            .apiKey(apiKey)
            .baseUrl(baseUrl)
            .timeout(timeout)
            .build();
    }
    
    // getters and setters...
}

// Service
@Service
public class EmailService {
    private final SparkMailrClient sparkMailrClient;
    
    public EmailService(SparkMailrClient sparkMailrClient) {
        this.sparkMailrClient = sparkMailrClient;
    }
    
    public String sendWelcomeEmail(String userEmail, String userName) {
        Map<String, Object> templateData = new HashMap<>();
        templateData.put("name", userName);
        templateData.put("activationLink", "https://app.example.com/activate");
        
        SendEmailRequest request = new SendEmailRequest.Builder()
            .to(Arrays.asList(userEmail))
            .from("noreply@yourapp.com")
            .templateId("welcome-template")
            .templateData(templateData)
            .build();
        
        EmailResponse response = sparkMailrClient.emails().send(request);
        return response.getId();
    }
}

C# .NET SDK

Modern .NET SDK supporting .NET 6.0+, ASP.NET Core integration, and Blazor compatibility.

NuGet Installation

# Package Manager
Install-Package SparkMailr.SDK

# .NET CLI
dotnet add package SparkMailr.SDK

Basic Usage

using SparkMailr;
using SparkMailr.Models;

// Initialize client
var client = new SparkMailrClient(new SparkMailrOptions 
{
    ApiKey = "your-api-key",
    Timeout = TimeSpan.FromSeconds(30)
});

try 
{
    // Send email
    var request = new SendEmailRequest
    {
        To = new[] { "user@example.com" },
        From = "noreply@yourapp.com",
        Subject = "Welcome to SparkMailr!",
        Html = "<h1>Hello World</h1>",
        Text = "Hello World"
    };
    
    var response = await client.Emails.SendAsync(request);
    Console.WriteLine($"Email sent: {response.Id}");
}
catch (SparkMailrException ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

ASP.NET Core Integration

// Program.cs (.NET 6+)
using SparkMailr.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add SparkMailr
builder.Services.AddSparkMailr(options =>
{
    options.ApiKey = builder.Configuration["SparkMailr:ApiKey"];
    options.BaseUrl = builder.Configuration["SparkMailr:BaseUrl"];
    options.Timeout = TimeSpan.FromSeconds(30);
});

var app = builder.Build();

// appsettings.json
{
  "SparkMailr": {
    "ApiKey": "your-api-key",
    "BaseUrl": "https://api.sparkmailr.com"
  }
}

// Controller
[ApiController]
[Route("api/[controller]")]
public class EmailController : ControllerBase
{
    private readonly ISparkMailrClient _sparkMailrClient;
    
    public EmailController(ISparkMailrClient sparkMailrClient)
    {
        _sparkMailrClient = sparkMailrClient;
    }
    
    [HttpPost("send-welcome")]
    public async Task<IActionResult> SendWelcomeEmail([FromBody] SendWelcomeRequest request)
    {
        var emailRequest = new SendEmailRequest
        {
            To = new[] { request.Email },
            From = "noreply@yourapp.com",
            TemplateId = "welcome-template",
            TemplateData = new Dictionary<string, object>
            {
                ["name"] = request.Name,
                ["activationLink"] = Url.Action("Activate", "Account", new { userId = request.UserId })
            }
        };
        
        var response = await _sparkMailrClient.Emails.SendAsync(emailRequest);
        return Ok(new { EmailId = response.Id });
    }
}

Go SDK

High-performance Go SDK with context support, functional options, and idiomatic Go patterns.

Installation

go get github.com/sparkmailr/go-sdk

Basic Usage

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/sparkmailr/go-sdk"
)

func main() {
    // Initialize client
    client := sparkmailr.NewClient("your-api-key",
        sparkmailr.WithTimeout(30),
        sparkmailr.WithBaseURL("https://api.sparkmailr.com"),
    )
    
    // Send email
    ctx := context.Background()
    response, err := client.Emails.Send(ctx, &sparkmailr.SendEmailRequest{
        To:      []string{"user@example.com"},
        From:    "noreply@yourapp.com",
        Subject: "Welcome to SparkMailr!",
        HTML:    "<h1>Hello World</h1>",
        Text:    "Hello World",
    })
    
    if err != nil {
        log.Fatalf("Error sending email: %v", err)
    }
    
    fmt.Printf("Email sent: %s\n", response.ID)
}

Advanced Usage with Context

package main

import (
    "context"
    "fmt"
    "time"
    
    "github.com/sparkmailr/go-sdk"
)

func sendBulkEmails() error {
    client := sparkmailr.NewClient("your-api-key")
    
    // Create context with timeout
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
    defer cancel()
    
    // Send template email
    templateResponse, err := client.Emails.Send(ctx, &sparkmailr.SendEmailRequest{
        To:           []string{"user@example.com"},
        From:         "noreply@yourapp.com",
        TemplateID:   "welcome-template",
        TemplateData: map[string]interface{}{
            "name":            "John Doe",
            "activation_link": "https://app.example.com/activate/123",
        },
    })
    if err != nil {
        return fmt.Errorf("failed to send template email: %w", err)
    }
    
    // Get email status
    status, err := client.Emails.GetStatus(ctx, templateResponse.ID)
    if err != nil {
        return fmt.Errorf("failed to get email status: %w", err)
    }
    
    fmt.Printf("Email %s status: %s\n", templateResponse.ID, status.Status)
    
    // Send bulk emails
    bulkRequest := &sparkmailr.BulkEmailRequest{
        From: "noreply@yourapp.com",
        HTML: "<h1>Newsletter</h1><p>Latest updates...</p>",
        Text: "Newsletter: Latest updates...",
        Emails: []sparkmailr.BulkEmailRecipient{
            {To: "user1@example.com", Subject: "Newsletter #1"},
            {To: "user2@example.com", Subject: "Newsletter #2"},
            {To: "user3@example.com", Subject: "Newsletter #3"},
        },
    }
    
    bulkResponse, err := client.Emails.SendBulk(ctx, bulkRequest)
    if err != nil {
        return fmt.Errorf("failed to send bulk emails: %w", err)
    }
    
    fmt.Printf("Bulk email batch: %s\n", bulkResponse.BatchID)
    
    // Get analytics
    analytics, err := client.Analytics.GetEmailStats(ctx, &sparkmailr.AnalyticsRequest{
        StartDate: time.Now().AddDate(0, -1, 0), // Last month
        EndDate:   time.Now(),
    })
    if err != nil {
        return fmt.Errorf("failed to get analytics: %w", err)
    }
    
    fmt.Printf("Total sent: %d, Delivery rate: %.2f%%\n", 
        analytics.TotalSent, analytics.DeliveryRate)
    
    return nil
}

// HTTP handler example
func emailHandler(w http.ResponseWriter, r *http.Request) {
    client := sparkmailr.NewClient(os.Getenv("SPARKMAILR_API_KEY"))
    
    ctx := r.Context()
    
    response, err := client.Emails.Send(ctx, &sparkmailr.SendEmailRequest{
        To:      []string{r.FormValue("email")},
        From:    "noreply@yourapp.com",
        Subject: "Contact Form Submission",
        HTML:    fmt.Sprintf("<p>Message: %s</p>", r.FormValue("message")),
    })
    
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    
    json.NewEncoder(w).Encode(map[string]string{
        "email_id": response.ID,
        "status":   "sent",
    })
}

Send Email API

The core endpoint for sending transactional emails through SparkMailr.

POST /api/v1/emails/send

Request Parameters

Parameter Type Required Description
to array Array of recipient email addresses
from string Sender email address
subject string Email subject line
html string ⚠️ HTML email content (required if text not provided)
text string ⚠️ Plain text email content

Email Tracking

SparkMailr provides comprehensive email tracking capabilities to monitor deliverability, engagement, and performance metrics.

Tracking Features

  • Delivery Tracking: Real-time delivery confirmation and bounce detection
  • Open Tracking: Pixel-based open tracking with privacy considerations
  • Click Tracking: Link click tracking and engagement analytics
  • Unsubscribe Tracking: Automatic unsubscribe link handling
  • Geolocation Data: IP-based location and device information

Get Email Status

GET /api/v1/emails/{email_id}/status
curl -X GET https://api.sparkmailr.com/v1/emails/em_1234567890/status \
  -H "Authorization: Bearer YOUR_API_KEY"

Status Response

{
  "email_id": "em_1234567890",
  "status": "delivered",
  "delivered_at": "2025-01-15T10:30:00Z",
  "opened_at": "2025-01-15T10:45:00Z",
  "clicked_at": "2025-01-15T10:50:00Z",
  "opens_count": 2,
  "clicks_count": 1,
  "last_activity": "2025-01-15T10:50:00Z",
  "recipient": "user@example.com",
  "ip_address": "192.168.1.1",
  "user_agent": "Mozilla/5.0...",
  "geolocation": {
    "country": "United States",
    "region": "California",
    "city": "San Francisco"
  }
}

Email Templates

Create, manage, and use reusable email templates to maintain consistent branding and accelerate development.

Create Template

POST /api/v1/templates
curl -X POST https://api.sparkmailr.com/v1/templates \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Welcome Email",
    "subject": "Welcome to {{company_name}}!",
    "html": "<h1>Welcome {{name}}!</h1><p>Thank you for joining {{company_name}}.</p>",
    "text": "Welcome {{name}}!\n\nThank you for joining {{company_name}}.",
    "variables": ["name", "company_name"]
  }'

Send with Template

POST /api/v1/emails/send
curl -X POST https://api.sparkmailr.com/v1/emails/send \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": ["user@example.com"],
    "from": "noreply@yourapp.com",
    "template_id": "welcome-template",
    "template_data": {
      "name": "John Doe",
      "company_name": "Your App",
      "activation_link": "https://yourapp.com/activate/123"
    }
  }'

Template Variables

Use double curly braces {{variable_name}} to define dynamic content in your templates.

Variable Type Syntax Example
Simple Text {{name}} John Doe
Conditional {{#if premium}}{{/if}} Show content for premium users
Loops {{#each items}}{{/each}} Iterate over arrays

Webhooks

Receive real-time notifications about email events including deliveries, bounces, and opens.

POST Your webhook endpoint

Event Types

  • delivered - Email was successfully delivered
  • bounced - Email bounced (hard or soft)
  • opened - Email was opened by recipient
  • clicked - Link in email was clicked
  • complained - Email was marked as spam
{
  "event": "delivered",
  "email_id": "em_1234567890",
  "recipient": "user@example.com",
  "timestamp": "2025-01-15T10:30:00Z",
  "metadata": {
    "campaign_id": "campaign_123",
    "user_id": "user_456"
  }
}

Analytics & Reporting

Get detailed insights into your email performance with comprehensive analytics and reporting tools.

Email Statistics

GET /api/v1/analytics/emails/stats
curl -X GET "https://api.sparkmailr.com/v1/analytics/emails/stats?start_date=2025-01-01&end_date=2025-01-31" \
  -H "Authorization: Bearer YOUR_API_KEY"

Analytics Response

{
  "period": {
    "start_date": "2025-01-01",
    "end_date": "2025-01-31"
  },
  "summary": {
    "sent": 1250,
    "delivered": 1220,
    "delivered_rate": 97.6,
    "opened": 380,
    "open_rate": 31.1,
    "clicked": 95,
    "click_rate": 7.8,
    "bounced": 25,
    "bounce_rate": 2.0,
    "complained": 3,
    "complaint_rate": 0.2
  },
  "trends": {
    "daily_stats": [
      {
        "date": "2025-01-01",
        "sent": 45,
        "delivered": 44,
        "opened": 12,
        "clicked": 3
      }
    ]
  },
  "top_performers": {
    "subjects": [
      {"subject": "Welcome to SparkMailr!", "open_rate": 35.2, "click_rate": 8.1}
    ],
    "domains": [
      {"domain": "gmail.com", "delivered_rate": 98.5, "open_rate": 32.1}
    ]
  }
}

Advanced Analytics

Enterprise plans include advanced analytics features:

  • Predictive Analytics: ML-powered delivery and engagement predictions
  • A/B Testing: Automated testing of subject lines and content
  • Cohort Analysis: User behavior segmentation over time
  • Revenue Attribution: Track email-driven conversions and revenue
  • Real-time Dashboards: Live performance monitoring

Export Data

GET /api/v1/analytics/export
curl -X GET "https://api.sparkmailr.com/v1/analytics/export?format=csv&start_date=2025-01-01&end_date=2025-01-31" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -o email_analytics.csv

Enterprise Features

SparkMailr provides enterprise-grade features for mission-critical applications. All enterprise features are available through our REST API and SDKs.

AI-Powered APIs

  • Send Time Optimization: POST /api/v1/ai/send-time/optimize
  • Content Generation: POST /api/v1/ai/content/generate
  • Predictive Analytics: GET /api/v1/analytics/predictive
  • Smart Subject Lines: POST /api/v1/ai/subject/optimize

Campaign Automation

  • Workflow Management: POST /api/v1/campaigns/workflows
  • A/B Testing: POST /api/v1/campaigns/ab-test
  • Conditional Logic: POST /api/v1/campaigns/conditions
  • Automation Rules: PUT /api/v1/campaigns/automation

Advanced Analytics

  • Funnel Analysis: POST /api/v1/analytics/funnel
  • Cohort Analysis: POST /api/v1/analytics/cohort
  • Report Generation: POST /api/v1/reports/generate
  • Real-time Dashboards: GET /api/v1/dashboards/realtime

Security & Compliance

  • Role-Based Access: POST /api/v1/security/rbac
  • Audit Logging: GET /api/v1/security/audit
  • Compliance Monitoring: GET /api/v1/compliance/status
  • Data Encryption: POST /api/v1/security/encrypt

Global Expansion

  • Cultural Adaptation: POST /api/v1/global/adapt
  • Send Time Optimization: POST /api/v1/global/send-times
  • Compliance Monitoring: GET /api/v1/global/compliance
  • Localization: POST /api/v1/global/localize

Enterprise Integrations

  • Salesforce Sync: POST /api/v1/integrations/salesforce
  • HubSpot Sync: POST /api/v1/integrations/hubspot
  • Webhook Management: POST /api/v1/webhooks
  • Custom Integrations: POST /api/v1/integrations/custom

Enterprise SDK Example

# Enterprise AI-powered email sending
import sparkmailr

client = sparkmailr.SparkMailrClient(
    api_key="your-enterprise-api-key",
    enterprise_mode=True
)

# AI-optimized email with predictive analytics
response = client.emails.send_enterprise({
    "to": ["customer@enterprise.com"],
    "from": "noreply@enterprise.com",
    "subject": "Personalized Offer",
    "ai_optimize": True,  # Enable AI optimization
    "predictive_analytics": True,  # Include engagement predictions
    "compliance_check": True,  # Ensure regulatory compliance
    "global_adaptation": "US",  # Cultural adaptation
    "html": "<h1>Your Personalized Enterprise Solution</h1>",
    "metadata": {
        "campaign_id": "enterprise-q4-2025",
        "customer_segment": "enterprise",
        "compliance_flags": ["gdpr", "ccpa"]
    }
})

print(f"AI-optimized email sent: {response.id}")
print(f"Predicted engagement: {response.predicted_engagement}%")
print(f"Compliance verified: {response.compliance_status}")

Phase 5 Market Leadership Features

AI & Automation

  • AI Content Studio
  • Intelligent Editor
  • Campaign Builder
  • Predictive Analytics

Innovation Lab

  • Voice Email
  • Video Email
  • AR/VR Designer
  • Interactive Builder

Enterprise Security

  • Security Health
  • Compliance Center
  • Blockchain Verification
  • Advanced RBAC

Global Expansion

  • Localization Console
  • Cultural Adaptation
  • Regulation Monitor
  • Performance Optimizer

Domain Setup

Proper domain configuration is essential for email deliverability. Set up SPF, DKIM, and DMARC records to authenticate your emails.

SPF (Sender Policy Framework)

Add this TXT record to your domain's DNS settings:

Host: yourdomain.com
Type: TXT
Value: "v=spf1 include:_spf.sparkmailr.com ~all"

DKIM (DomainKeys Identified Mail)

Add this CNAME record for DKIM signing:

Host: sparkmailr._domainkey.yourdomain.com
Type: CNAME
Value: dkim.sparkmailr.com

DMARC (Domain-based Message Authentication)

Add this TXT record for DMARC policy:

Host: _dmarc.yourdomain.com
Type: TXT
Value: "v=DMARC1; p=quarantine; rua=mailto:dmarc@yourdomain.com; ruf=mailto:dmarc@yourdomain.com"

Verify Domain Setup

POST /api/v1/domains/verify
curl -X POST https://api.sparkmailr.com/v1/domains/verify \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "domain": "yourdomain.com"
  }'

⚠️ DNS Propagation

DNS changes may take up to 24-48 hours to propagate globally. Use tools like MX Toolbox to verify your records.

Email Validation

Validate email addresses before sending to improve deliverability and reduce bounce rates.

Validate Single Email

POST /api/v1/emails/validate
curl -X POST https://api.sparkmailr.com/v1/emails/validate \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com"
  }'

Batch Email Validation

curl -X POST https://api.sparkmailr.com/v1/emails/validate-batch \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "emails": [
      "user1@example.com",
      "user2@example.com",
      "invalid-email"
    ]
  }'

Validation Response

{
  "email": "user@example.com",
  "valid": true,
  "score": 0.95,
  "checks": {
    "syntax": true,
    "domain": true,
    "mx_records": true,
    "smtp_check": true,
    "disposable": false,
    "role_account": false
  },
  "reason": "Valid email address"
}

Validation Checks

Check Type Description
Syntax Valid email format (RFC compliance)
Domain Domain exists and is resolvable
MX Records Mail exchange records configured
SMTP Check Mailbox exists (catch-all detection)
Disposable Not a temporary/disposable email
Role Account Not a role-based email (noreply, admin, etc.)

Best Practices

1. Email Authentication

Always set up proper SPF, DKIM, and DMARC records for your sending domains to improve deliverability.

2. Rate Limiting

Respect rate limits and implement exponential backoff for retries. The default rate limit is 100 requests per minute.

3. Error Handling

Always handle errors gracefully and implement proper logging for failed email sends.

# Python example with error handling
try:
    response = client.emails.send(email_data)
    logger.info(f"Email sent successfully: {response.id}")
except sparkmailr.AuthenticationError:
    logger.error("Invalid API key")
except sparkmailr.RateLimitError as e:
    logger.warning(f"Rate limited. Retry after: {e.retry_after}")
except sparkmailr.ValidationError as e:
    logger.error(f"Validation failed: {e.details}")
except Exception as e:
    logger.error(f"Unexpected error: {str(e)}")

4. Template Usage

Use templates for consistent branding and easier maintenance of email content.

5. Analytics Monitoring

Regularly monitor your email analytics to optimize delivery rates and engagement.

Troubleshooting

Common Issues

Authentication Errors (401)

Cause: Invalid or missing API key

Solution: Check your API key and ensure it's correctly set in the Authorization header

Rate Limit Exceeded (429)

Cause: Too many requests in a short time

Solution: Implement exponential backoff and respect the retry-after header

Email Not Delivered

Causes: Invalid recipient, domain authentication issues, or content flagged as spam

Solution: Check email validation, verify domain setup, and review content guidelines

Need More Help?

Can't find what you're looking for? Our enterprise support team is here to help 24/7.

Enterprise Support Developer Support System Status