Email API Guide: Everything You Need to Know with Code Examples
Complete guide to email APIs: how they work, implementation examples, best practices, and choosing the right solution for your application.
Email APIs allow developers to programmatically send, receive, and manage emails from applications. Whether you're sending order confirmations, password resets, or marketing campaigns, email APIs provide a reliable, scalable way to integrate email into your software.
This guide covers everything you need to know: how email APIs work, implementation examples in multiple languages, best practices, and choosing the right provider.
What is an Email API?
An email API is a programmatic interface that lets you send and manage emails via HTTP requests instead of manually configuring SMTP servers. APIs abstract away the complexity of email delivery, providing simple HTTP endpoints to send emails and webhooks to track delivery status.
SMTP (Traditional)
- • Direct protocol for sending email
- • Requires managing connections
- • Manual error handling
- • Limited delivery tracking
- • More complex implementation
- • Port 25, 587, or 465
Email API (Modern)
- • HTTP-based RESTful interface
- • No connection management needed
- • Structured error responses
- • Built-in tracking & analytics
- • Simpler to implement
- • Standard HTTP/HTTPS
When to Use Email APIs
Email APIs are ideal for transactional emails (order confirmations, password resets), automated notifications, and programmatic campaigns. If you're building software that sends emails, APIs are almost always the better choice over SMTP.
How Email APIs Work
1. Authentication
You authenticate requests using an API key (usually passed in headers). This identifies your account and authorizes API access.
2. Make HTTP Request
Send a POST request to the API endpoint with email details (recipient, subject, body, etc.) as JSON.
3. API Validates & Queues
The API validates your request, queues the email for delivery, and returns a response with the email ID and status.
4. Email Delivery
The service handles SMTP connections, retry logic, and delivery to the recipient's mail server.
5. Webhooks & Tracking
You receive webhook notifications for delivery events (delivered, bounced, opened, clicked) and can query the API for email status.
Email API Code Examples
Here's how to send an email using Plunk's API in various languages:
JavaScript / Node.js
// Using fetch (Node.js 18+ or with node-fetch)
const response = await fetch('https://api.useplunk.com/v1/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
to: 'user@example.com',
subject: 'Welcome to our platform!',
body: '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
// Optional fields
from: 'noreply@yourdomain.com',
name: 'Your Company',
replyTo: 'support@yourdomain.com'
})
});
const data = await response.json();
if (response.ok) {
console.log('Email sent!', data.emailId);
} else {
console.error('Failed to send:', data.error);
}Python
import requests
response = requests.post(
'https://api.useplunk.com/v1/send',
headers={
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
json={
'to': 'user@example.com',
'subject': 'Welcome to our platform!',
'body': '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
'from': 'noreply@yourdomain.com',
'name': 'Your Company'
}
)
if response.status_code == 200:
data = response.json()
print(f"Email sent! ID: {data['emailId']}")
else:
print(f"Error: {response.json()['error']}")PHP
<?php
$ch = curl_init('https://api.useplunk.com/v1/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer YOUR_API_KEY'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'to' => 'user@example.com',
'subject' => 'Welcome to our platform!',
'body' => '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
'from' => 'noreply@yourdomain.com',
'name' => 'Your Company'
]));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($response, true);
if ($httpCode === 200) {
echo "Email sent! ID: " . $data['emailId'];
} else {
echo "Error: " . $data['error'];
}
?>Ruby
require 'net/http'
require 'json'
uri = URI('https://api.useplunk.com/v1/send')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path)
request['Content-Type'] = 'application/json'
request['Authorization'] = 'Bearer YOUR_API_KEY'
request.body = {
to: 'user@example.com',
subject: 'Welcome to our platform!',
body: '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
from: 'noreply@yourdomain.com',
name: 'Your Company'
}.to_json
response = http.request(request)
data = JSON.parse(response.body)
if response.code.to_i == 200
puts "Email sent! ID: #{data['emailId']}"
else
puts "Error: #{data['error']}"
endGo
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type EmailRequest struct {
To string `json:"to"`
Subject string `json:"subject"`
Body string `json:"body"`
From string `json:"from"`
Name string `json:"name"`
}
func main() {
email := EmailRequest{
To: "user@example.com",
Subject: "Welcome to our platform!",
Body: "<h1>Welcome!</h1><p>Thanks for signing up.</p>",
From: "noreply@yourdomain.com",
Name: "Your Company",
}
jsonData, _ := json.Marshal(email)
req, _ := http.NewRequest("POST", "https://api.useplunk.com/v1/send", bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode == 200 {
var result map[string]interface{}
json.Unmarshal(body, &result)
fmt.Printf("Email sent! ID: %v\n", result["emailId"])
} else {
fmt.Println("Error:", string(body))
}
}Common Email API Features
Sending Features
- • Send individual or batch emails
- • HTML and plain text support
- • Attachments
- • CC, BCC recipients
- • Custom headers
- • Template rendering
- • Scheduled sending
Tracking & Analytics
- • Delivery status tracking
- • Open tracking
- • Click tracking
- • Bounce detection
- • Spam complaint monitoring
- • Unsubscribe management
- • Real-time analytics
Webhooks & Events
- • Delivery notifications
- • Bounce notifications
- • Spam complaint alerts
- • Unsubscribe events
- • Open and click events
- • Custom event triggers
Management Features
- • Suppression list management
- • Contact management
- • Domain verification
- • Template management
- • API key management
- • Rate limiting
Email API Best Practices
Secure Your API Keys
Store API keys in environment variables, never in code. Use separate keys for development, staging, and production. Rotate keys periodically and immediately if compromised.
Implement Proper Error Handling
Handle different HTTP status codes appropriately:
- 200: Success
- 400-499: Client errors (bad request, validation failed) - don't retry
- 500-599: Server errors - retry with exponential backoff
- 429: Rate limit exceeded - back off and retry later
Use Webhooks for Delivery Status
Don't poll the API for email status. Set up webhooks to receive real-time delivery notifications (delivered, bounced, opened, clicked). This is more efficient and provides faster updates.
Respect Rate Limits
Implement rate limiting in your code to stay within API limits. Queue emails and send in batches. Use exponential backoff when you receive 429 rate limit errors.
Validate Email Addresses
Validate email format before making API calls. Check for common typos. Consider using email validation APIs to verify deliverability before sending.
Use Templates
Store email templates in your email service provider rather than hardcoding HTML in your application. This allows non-developers to update email content without code changes.
Monitor Deliverability Metrics
Track bounce rates, spam complaints, and engagement metrics. Set up alerts for anomalies. Address deliverability issues proactively.
Test in Sandbox/Development Mode
Use sandbox or test mode during development. Test error scenarios, retry logic, and webhook handling before deploying to production.
Log API Requests & Responses
Log all API interactions (but redact sensitive data like API keys). This helps debug issues and understand email sending patterns.
Handle Timeouts
Set appropriate timeouts for API requests (typically 10-30 seconds). Don't block user requests waiting for email API responses—queue emails asynchronously if needed.
Choosing an Email API Provider
Consider these factors when selecting an email API provider:
Deliverability Reputation
Choose providers with strong deliverability rates and sender reputation. Poor deliverability means your emails land in spam, defeating the purpose.
Feature Set
Ensure the API supports your needs: templates, webhooks, analytics, scheduling, attachments, etc. Some providers specialize in transactional emails, others in marketing.
Pricing Model
Understand pricing: per-email charges, monthly tiers, overage fees. Calculate costs for your expected volume. Watch for hidden fees and price increases at higher volumes.
Developer Experience
Good documentation, SDKs in your language, clear error messages, and responsive support make implementation much easier.
Scalability & Reliability
Can the provider handle your peak volumes? What's their uptime guarantee (SLA)? Do they have redundancy and failover systems?
Compliance & Security
Ensure the provider complies with GDPR, CAN-SPAM, and other relevant regulations. Check their security certifications (SOC 2, ISO 27001).