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
Authentication
SparkMailr uses API keys for authentication. You can generate an API key from your dashboard.
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
"
}'
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'
});
console.log(`Email sent: ${response.id}`);
} 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);
console.log(`Status: ${status.status}`);
// 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'
});
console.log(`Total sent: ${analytics.sent}`);
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.
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 |
Webhooks
Receive real-time notifications about email events including deliveries, bounces, and opens.
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"
}
}
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 support team is here to help.
Contact Support