# Create Domain
Source: https://docs.unosend.co/api-reference/domains/create-domain
POST /domains
Add a new sending domain to your account.
The domain name to add (e.g., "yourdomain.com").
### Request
```bash cURL theme={null}
curl -X POST https://api.unosend.co/domains \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"name": "yourdomain.com"
}'
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/domains', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_xxxxxxxxxx',
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'yourdomain.com' })
});
```
```python Python theme={null}
import requests
requests.post('https://api.unosend.co/domains',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'},
json={'name': 'yourdomain.com'}
)
```
### Response
```json 201 theme={null}
{
"success": true,
"data": {
"id": "dom_123",
"domain": "yourdomain.com",
"status": "pending",
"dns_records": [
{
"type": "TXT",
"name": "@",
"value": "v=spf1 include:spf.unosend.co ~all",
"purpose": "spf"
},
{
"type": "CNAME",
"name": "bounce",
"value": "cname.unosend.co",
"purpose": "bounce"
}
],
"created_at": "2024-01-15T10:30:00.000Z"
}
}
```
After creating a domain, add the provided DNS records to your domain provider, then call the verify endpoint.
All plans include **unlimited domains**. Domain creation is rate limited to 10 per hour per organization to prevent abuse.
# Delete Domain
Source: https://docs.unosend.co/api-reference/domains/delete-domain
DELETE /domains/{id}
Remove a domain from your account.
The ID of the domain to delete.
### Request
```bash cURL theme={null}
curl -X DELETE https://api.unosend.co/domains/dom_123 \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/domains/dom_123', {
method: 'DELETE',
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
```
```python Python theme={null}
import requests
requests.delete('https://api.unosend.co/domains/dom_123',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'}
)
```
### Response
```json 200 theme={null}
{
"success": true,
"data": {
"id": "dom_123"
}
}
```
Deleting a domain will prevent you from sending emails from that domain. This action cannot be undone.
# Retrieve Domain
Source: https://docs.unosend.co/api-reference/domains/get-domain
GET /domains/{id}
Retrieve a domain by ID.
The ID of the domain to retrieve.
### Request
```bash cURL theme={null}
curl https://api.unosend.co/domains/dom_123 \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/domains/dom_123', {
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
```
```python Python theme={null}
import requests
requests.get('https://api.unosend.co/domains/dom_123',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'}
)
```
### Response
```json 200 theme={null}
{
"success": true,
"data": {
"id": "dom_123",
"domain": "yourdomain.com",
"status": "verified",
"dns_records": [
{
"type": "TXT",
"name": "_unosend",
"value": "unosend-verification=abc123",
"purpose": "verification",
"verified": true
}
],
"created_at": "2024-01-15T10:30:00.000Z",
"verified_at": "2024-01-15T11:00:00.000Z"
}
}
```
# List Domains
Source: https://docs.unosend.co/api-reference/domains/list-domains
GET /domains
List all domains in your account.
### Request
```bash cURL theme={null}
curl https://api.unosend.co/domains \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/domains', {
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
```
```python Python theme={null}
import requests
requests.get('https://api.unosend.co/domains',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'}
)
```
### Response
```json 200 theme={null}
{
"success": true,
"data": [
{
"id": "dom_123",
"domain": "yourdomain.com",
"status": "verified",
"created_at": "2024-01-15T10:30:00.000Z"
},
{
"id": "dom_124",
"domain": "anotherdomain.com",
"status": "pending",
"created_at": "2024-01-16T10:30:00.000Z"
}
]
}
```
# Verify Domain
Source: https://docs.unosend.co/api-reference/domains/verify-domain
POST /domains/{id}/verify
Verify domain DNS records.
The ID of the domain to verify.
### Request
```bash cURL theme={null}
curl -X POST https://api.unosend.co/domains/dom_123/verify \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/domains/dom_123/verify', {
method: 'POST',
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
```
```python Python theme={null}
import requests
requests.post('https://api.unosend.co/domains/dom_123/verify',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'}
)
```
### Response
```json 200 theme={null}
{
"id": "dom_123",
"domain": "yourdomain.com",
"status": "verified",
"dns_records": [
{
"type": "TXT",
"name": "_unosend",
"value": "unosend-verification=abc123",
"purpose": "verification",
"verified": true
},
{
"type": "TXT",
"name": "@",
"value": "v=spf1 include:_spf.unosend.co ~all",
"purpose": "spf",
"verified": true
}
],
"verified_at": "2024-01-15T11:00:00.000Z"
}
```
DNS changes can take up to 48 hours to propagate. If verification fails, try again later.
# Export Logs
Source: https://docs.unosend.co/api-reference/emails/exports
POST /v1/exports
Export email logs, bounce reports, or delivery data as downloadable files.
Create an export job to download email delivery data in CSV format.
Type of export: `email_logs`, `bounces`, `suppressions`, or `opens`.
Start date in ISO 8601 format.
End date in ISO 8601 format.
Filter by sending domain. Optional.
### Request
```bash cURL theme={null}
curl -X POST https://api.unosend.co/v1/exports \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"type": "email_logs",
"from_date": "2026-01-01T00:00:00Z",
"to_date": "2026-01-31T23:59:59Z"
}'
```
### Response
```json 202 theme={null}
{
"message": "Export job created",
"data": {
"export_id": "exp_abc123",
"type": "email_logs",
"status": "processing",
"created_at": "2026-01-15T10:30:00.000Z"
}
}
```
***
## List Exports
GET /v1/exports
Fetch all export jobs and their statuses.
```bash cURL theme={null}
curl -X GET https://api.unosend.co/v1/exports \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
### Response
```json 200 theme={null}
{
"data": [
{
"export_id": "exp_abc123",
"type": "email_logs",
"status": "completed",
"download_url": "https://api.unosend.co/v1/exports/exp_abc123/download",
"created_at": "2026-01-15T10:30:00.000Z",
"expires_at": "2026-01-22T10:30:00.000Z"
}
]
}
```
***
## Download Export
GET /v1/exports//download
Download a completed export file.
```bash cURL theme={null}
curl -X GET https://api.unosend.co/v1/exports/exp_abc123/download \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-o email_logs.csv
```
Export download links expire after **7 days**. Create a new export if the link has expired.
***
## Delete Export
DELETE /v1/exports
Delete one or more completed exports.
```bash cURL theme={null}
curl -X DELETE "https://api.unosend.co/v1/exports?export_ids=exp_abc123,exp_def456" \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
### Response
```json 200 theme={null}
{
"message": "Exports deleted",
"deleted": ["exp_abc123", "exp_def456"]
}
```
# Retrieve Email
Source: https://docs.unosend.co/api-reference/emails/get-email
GET /emails/{id}
Retrieve a sent email by ID.
The ID of the email to retrieve.
### Request
```bash cURL theme={null}
curl https://api.unosend.co/emails/550e8400-e29b-41d4-a716-446655440000 \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.unosend.co/emails/550e8400-e29b-41d4-a716-446655440000', {
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
const email = await response.json();
```
```python Python theme={null}
import requests
response = requests.get('https://api.unosend.co/emails/550e8400-e29b-41d4-a716-446655440000',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'}
)
email = response.json()
```
```go Go theme={null}
req, _ := http.NewRequest("GET", "https://api.unosend.co/emails/550e8400-e29b-41d4-a716-446655440000", nil)
req.Header.Set("Authorization", "Bearer un_xxxxxxxxxx")
resp, _ := http.DefaultClient.Do(req)
```
```php PHP theme={null}
$ch = curl_init('https://api.unosend.co/emails/550e8400-e29b-41d4-a716-446655440000');
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => ['Authorization: Bearer un_xxxxxxxxxx'],
CURLOPT_RETURNTRANSFER => true
]);
$response = curl_exec($ch);
```
```ruby Ruby theme={null}
require 'net/http'
uri = URI('https://api.unosend.co/emails/550e8400-e29b-41d4-a716-446655440000')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = 'Bearer un_xxxxxxxxxx'
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
```
### Response
```json 200 theme={null}
{
"success": true,
"data": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"from": "hello@yourdomain.com",
"to": ["user@example.com"],
"subject": "Hello World",
"html": "
Welcome!
",
"status": "delivered",
"created_at": "2024-01-15T10:30:00.000Z",
"delivered_at": "2024-01-15T10:30:05.000Z"
}
}
```
Unique email identifier.
Sender email address.
Recipient email addresses.
Email subject line.
HTML content of the email.
Delivery status: `queued`, `sent`, `delivered`, `bounced`, `complained`.
When the email was created (ISO 8601).
When the email was delivered (ISO 8601). `null` if not yet delivered.
# List Sent Emails
Source: https://docs.unosend.co/api-reference/emails/list-emails
GET /emails
List all sent emails with pagination.
Page number.
Number of emails per page (max 100).
Filter by status: `queued`, `sent`, `delivered`, `bounced`, `complained`.
### Request
```bash cURL theme={null}
curl "https://api.unosend.co/emails?page=1&per_page=10" \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.unosend.co/emails?page=1&per_page=10', {
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.get('https://api.unosend.co/emails',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'},
params={'page': 1, 'per_page': 10}
)
data = response.json()
```
```go Go theme={null}
req, _ := http.NewRequest("GET", "https://api.unosend.co/emails?page=1&per_page=10", nil)
req.Header.Set("Authorization", "Bearer un_xxxxxxxxxx")
resp, _ := http.DefaultClient.Do(req)
```
```php PHP theme={null}
$ch = curl_init('https://api.unosend.co/emails?page=1&per_page=10');
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => ['Authorization: Bearer un_xxxxxxxxxx'],
CURLOPT_RETURNTRANSFER => true
]);
$response = curl_exec($ch);
```
```ruby Ruby theme={null}
require 'net/http'
uri = URI('https://api.unosend.co/emails?page=1&per_page=10')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = 'Bearer un_xxxxxxxxxx'
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
```
### Response
```json 200 theme={null}
{
"success": true,
"data": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"from": "hello@yourdomain.com",
"to": ["user@example.com"],
"subject": "Hello World",
"status": "delivered",
"created_at": "2024-01-15T10:30:00.000Z"
}
],
"meta": {
"total": 42,
"page": 1,
"page_size": 10,
"pages": 5
}
}
```
Whether the request was successful.
Array of email objects.
Unique email identifier.
Sender email address.
Recipient email addresses.
Email subject line.
Delivery status: `queued`, `sent`, `delivered`, `bounced`, `complained`.
ISO 8601 timestamp.
Pagination metadata.
Total number of emails.
Current page number.
Number of results per page.
Total number of pages.
# Send Batch Emails
Source: https://docs.unosend.co/api-reference/emails/send-batch
POST /emails/batch
Send multiple emails in a single API call (up to 100 emails).
Array of email objects. Each email has the same structure as the single send endpoint, including `from`, `to`, `subject`, `html`, `text`, and `tracking`.
Each email in the batch can have its own tracking settings. See [Email Tracking](/api-reference/tracking) for details.
### Request
```bash cURL theme={null}
curl -X POST https://api.unosend.co/emails/batch \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"emails": [
{
"from": "hello@yourdomain.com",
"to": ["user1@example.com"],
"subject": "Welcome User 1",
"html": "Hello User 1!
",
"tracking": {
"open": true,
"click": false
}
},
{
"from": "hello@yourdomain.com",
"to": ["user2@example.com"],
"subject": "Welcome User 2",
"html": "Hello User 2!
",
"tracking": {
"open": true,
"click": true
}
}
]
}'
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/emails/batch', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_xxxxxxxxxx',
'Content-Type': 'application/json'
},
body: JSON.stringify({
emails: [
{
from: 'hello@yourdomain.com',
to: ['user1@example.com'],
subject: 'Welcome User 1',
html: 'Hello User 1!
',
tracking: { open: true, click: false }
},
{
from: 'hello@yourdomain.com',
to: ['user2@example.com'],
subject: 'Welcome User 2',
html: 'Hello User 2!
',
tracking: { open: true, click: true }
}
]
})
});
```
```python Python theme={null}
import requests
requests.post('https://api.unosend.co/emails/batch',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'},
json={
'emails': [
{
'from': 'hello@yourdomain.com',
'to': ['user1@example.com'],
'subject': 'Welcome User 1',
'html': 'Hello User 1!
',
'tracking': {'open': True, 'click': False}
},
{
'from': 'hello@yourdomain.com',
'to': ['user2@example.com'],
'subject': 'Welcome User 2',
'html': 'Hello User 2!
',
'tracking': {'open': True, 'click': True}
}
]
}
)
```
### Response
```json 200 theme={null}
{
"success": true,
"data": {
"data": [
{
"id": "550e8400-e29b-41d4-a716-446655440001"
},
{
"id": "550e8400-e29b-41d4-a716-446655440002"
}
]
}
}
```
# Send Email
Source: https://docs.unosend.co/api-reference/emails/send-email
POST /emails
Send an email to one or more recipients.
Sender email address. Must be from a verified domain. Can include a name: `"John Doe "`.
Recipient email address(es).
Email subject line.
HTML content of the email. Required unless `text` or `template_id` is provided.
Plain text content of the email.
UUID of a saved template to use. If provided, the template's content will be used.
Variables to replace in the template. Example: `{"first_name": "John", "order_id": "12345"}`.
CC recipient(s).
BCC recipient(s).
Reply-to email address.
Email priority: `high` (OTP/transactional, fastest delivery), `normal` (default), or `low` (bulk/marketing).
Array of attachments. Each attachment has `filename`, `content` (base64), and `content_type`.
Custom email headers.
Custom tags for analytics. Each tag has `name` and `value`.
ISO 8601 datetime for scheduled sending.
Control email tracking behavior.
Enable open tracking. When `true`, a 1x1 invisible pixel is added to track email opens.
Enable click tracking. When `true`, links are rewritten to track clicks.
### Request
```bash cURL theme={null}
curl -X POST https://api.unosend.co/emails \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"from": "hello@yourdomain.com",
"to": ["user@example.com"],
"subject": "Hello World",
"html": "Welcome!
Thanks for signing up.
",
"tracking": {
"open": true,
"click": false
}
}'
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/emails', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_xxxxxxxxxx',
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: 'hello@yourdomain.com',
to: ['user@example.com'],
subject: 'Hello World',
html: 'Welcome!
Thanks for signing up.
',
tracking: {
open: true,
click: false
}
})
});
```
```python Python theme={null}
import requests
requests.post('https://api.unosend.co/emails',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'},
json={
'from': 'hello@yourdomain.com',
'to': ['user@example.com'],
'subject': 'Hello World',
'html': 'Welcome!
Thanks for signing up.
',
'tracking': {
'open': True,
'click': False
}
}
)
```
```go Go theme={null}
payload := map[string]interface{}{
"from": "hello@yourdomain.com",
"to": []string{"user@example.com"},
"subject": "Hello World",
"html": "Welcome!
Thanks for signing up.
",
"tracking": map[string]bool{
"open": true,
"click": false,
},
}
body, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", "https://api.unosend.co/emails", bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer un_xxxxxxxxxx")
req.Header.Set("Content-Type", "application/json")
```
```php PHP theme={null}
$ch = curl_init('https://api.unosend.co/emails');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer un_xxxxxxxxxx', 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'from' => 'hello@yourdomain.com',
'to' => ['user@example.com'],
'subject' => 'Hello World',
'html' => 'Welcome!
Thanks for signing up.
',
'tracking' => [
'open' => true,
'click' => false
]
])
]);
curl_exec($ch);
```
```ruby Ruby theme={null}
require 'net/http'
require 'json'
uri = URI('https://api.unosend.co/emails')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri)
request['Authorization'] = 'Bearer un_xxxxxxxxxx'
request['Content-Type'] = 'application/json'
request.body = {
from: 'hello@yourdomain.com',
to: ['user@example.com'],
subject: 'Hello World',
html: 'Welcome!
Thanks for signing up.
'
}.to_json
http.request(request)
```
### Response
```json 200 theme={null}
{
"success": true,
"data": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"from": "hello@yourdomain.com",
"to": ["user@example.com"],
"status": "queued",
"created_at": "2024-01-15T10:30:00.000Z"
}
}
```
# Send Batch with Template
Source: https://docs.unosend.co/api-reference/emails/send-template-batch
POST /v1/email/template/batch
Send multiple templated emails in a single API call with individual merge data per recipient.
The unique key of the template to use for all emails in the batch.
Sender details with `address` and optional `name`.
Array of recipient objects. Each recipient can have their own `merge_info`.
Recipient email address.
Recipient display name.
Per-recipient template variables.
### Request
```bash cURL theme={null}
curl -X POST https://api.unosend.co/v1/email/template/batch \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"template_key": "order-confirmation",
"from": {
"address": "orders@yourdomain.com",
"name": "Your Store"
},
"to": [
{
"email_address": {
"address": "user1@example.com",
"name": "Alice"
},
"merge_info": {
"first_name": "Alice",
"order_id": "ORD-001"
}
},
{
"email_address": {
"address": "user2@example.com",
"name": "Bob"
},
"merge_info": {
"first_name": "Bob",
"order_id": "ORD-002"
}
}
]
}'
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/v1/email/template/batch', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_xxxxxxxxxx',
'Content-Type': 'application/json'
},
body: JSON.stringify({
template_key: 'order-confirmation',
from: { address: 'orders@yourdomain.com', name: 'Your Store' },
to: [
{ email_address: { address: 'user1@example.com', name: 'Alice' }, merge_info: { first_name: 'Alice', order_id: 'ORD-001' } },
{ email_address: { address: 'user2@example.com', name: 'Bob' }, merge_info: { first_name: 'Bob', order_id: 'ORD-002' } }
]
})
});
```
### Response
```json 200 theme={null}
{
"message": "OK",
"request_id": "req_batch_789xyz",
"data": [
{ "message_id": "msg_001", "recipient": "user1@example.com", "status": "queued" },
{ "message_id": "msg_002", "recipient": "user2@example.com", "status": "queued" }
]
}
```
Each recipient in the batch uses 1 credit. A batch of 50 recipients consumes 50 credits.
# Send Email with Template
Source: https://docs.unosend.co/api-reference/emails/send-template-email
POST /v1/email/template
Send an email using a pre-configured template with dynamic merge fields.
The unique key of the template to use.
Sender details.
Sender email address. Must be from a verified domain.
Sender display name.
Array of recipient objects.
Recipient email address.
Recipient display name.
Key-value pairs for template variable substitution. Example: `{"first_name": "John", "order_id": "12345"}`.
Reply-to address with `address` and optional `name`.
CC recipients. Same structure as `to`.
BCC recipients. Same structure as `to`.
### Request
```bash cURL theme={null}
curl -X POST https://api.unosend.co/v1/email/template \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"template_key": "welcome-email",
"from": {
"address": "hello@yourdomain.com",
"name": "Your App"
},
"to": [
{
"email_address": {
"address": "user@example.com",
"name": "John Doe"
}
}
],
"merge_info": {
"first_name": "John",
"activation_link": "https://yourapp.com/activate/abc123"
}
}'
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/v1/email/template', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_xxxxxxxxxx',
'Content-Type': 'application/json'
},
body: JSON.stringify({
template_key: 'welcome-email',
from: { address: 'hello@yourdomain.com', name: 'Your App' },
to: [{ email_address: { address: 'user@example.com', name: 'John Doe' } }],
merge_info: { first_name: 'John', activation_link: 'https://yourapp.com/activate/abc123' }
})
});
```
```python Python theme={null}
import requests
requests.post('https://api.unosend.co/v1/email/template',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'},
json={
'template_key': 'welcome-email',
'from': {'address': 'hello@yourdomain.com', 'name': 'Your App'},
'to': [{'email_address': {'address': 'user@example.com', 'name': 'John Doe'}}],
'merge_info': {'first_name': 'John', 'activation_link': 'https://yourapp.com/activate/abc123'}
}
)
```
### Response
```json 200 theme={null}
{
"message": "OK",
"request_id": "req_abc123def456",
"data": {
"message_id": "msg_550e8400e29b41d4"
}
}
```
Template variables use the `{{variable_name}}` syntax. Make sure all required variables in the template are provided in `merge_info`.
# Upload File
Source: https://docs.unosend.co/api-reference/emails/upload-file
POST /v1/files
Upload a file to the cache for use as an attachment or inline image across multiple emails.
Upload files to Unosend's file cache and reuse them across multiple email sends without re-uploading. Cached files are referenced by their `file_cache_key` in subsequent API calls.
The filename including extension (e.g., `logo.png`, `invoice.pdf`).
The file content as multipart/form-data.
### Request
```bash cURL theme={null}
curl -X POST "https://api.unosend.co/v1/files?name=logo.png" \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-F "file=@/path/to/logo.png"
```
```javascript JavaScript theme={null}
const formData = new FormData();
formData.append('file', fileBlob, 'logo.png');
await fetch('https://api.unosend.co/v1/files?name=logo.png', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_xxxxxxxxxx'
},
body: formData
});
```
```python Python theme={null}
import requests
with open('logo.png', 'rb') as f:
requests.post(
'https://api.unosend.co/v1/files?name=logo.png',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'},
files={'file': ('logo.png', f, 'image/png')}
)
```
### Response
```json 200 theme={null}
{
"message": "OK",
"data": {
"file_cache_key": "fc_1a2b3c4d5e6f",
"name": "logo.png",
"size": 24576,
"content_type": "image/png",
"created_at": "2026-01-15T10:30:00.000Z"
}
}
```
## Using Cached Files in Emails
Reference the `file_cache_key` when sending emails:
```json theme={null}
{
"from": {"address": "hello@yourdomain.com", "name": "Your App"},
"to": [{"email_address": {"address": "user@example.com"}}],
"subject": "Your Invoice",
"htmlbody": "Please find your invoice attached.
",
"attachments": [
{
"file_cache_key": "fc_1a2b3c4d5e6f",
"name": "invoice.pdf"
}
]
}
```
### Inline Images
Use `cid` to embed images inline in HTML:
```json theme={null}
{
"htmlbody": "
",
"inline_images": [
{
"file_cache_key": "fc_1a2b3c4d5e6f",
"cid": "logo"
}
]
}
```
* Maximum file size: **10 MB**
* Total email size (headers + body + attachments): **15 MB**
* Cached files are stored for **30 days** from last use
# Introduction
Source: https://docs.unosend.co/api-reference/introduction
Understand general concepts, response codes, and authentication strategies.
## Base URL
The Unosend API is built on **REST** principles. We enforce **HTTPS** in every request to improve data security, integrity, and privacy. The API does not support **HTTP**.
All requests contain the following base URL:
```
https://api.unosend.co
```
## Authentication
To authenticate you need to add an `Authorization` header with the contents of the header being `Bearer un_xxxxxxxxxx` where `un_xxxxxxxxxx` is your **API Key**.
```
Authorization: Bearer un_xxxxxxxxxx
```
Keep your API key secure and never expose it in client-side code.
## Response codes
Unosend uses standard HTTP codes to indicate the success or failure of your requests.
In general, `2xx` HTTP codes correspond to success, `4xx` codes are for user-related failures, and `5xx` codes are for infrastructure issues.
| Status | Description |
| ------ | ----------------------------------------------------- |
| `200` | Successful request. |
| `400` | Check that the parameters were correct. |
| `401` | The API key used was missing or invalid. |
| `403` | The API key doesn't have permissions for the request. |
| `404` | The requested resource was not found. |
| `422` | Unprocessable entity. Check the request body. |
| `429` | The rate limit was exceeded. |
| `500` | Internal server error. |
## Rate limit
The API has a rate limit of **100 requests per second**. If you exceed this limit, you'll receive a `429` response.
Rate limit headers are included in all responses:
| Header | Description |
| ----------------------- | ------------------------------------- |
| `X-RateLimit-Limit` | Maximum requests per window |
| `X-RateLimit-Remaining` | Requests remaining in current window |
| `X-RateLimit-Reset` | Unix timestamp when the window resets |
## Pagination
List endpoints support pagination using `limit` and `offset` query parameters:
```bash theme={null}
GET /emails?limit=20&offset=40
```
| Parameter | Type | Default | Description |
| --------- | ------- | ------- | ---------------------------------- |
| `limit` | integer | 20 | Number of items per page (max 100) |
| `offset` | integer | 0 | Number of items to skip |
## FAQ
Unosend API keys start with `un_` prefix for easy identification.
No, API requests should only be made from your server to keep your API key secure. Never expose your API key in client-side code.
The maximum total email size (headers + body + inline images + attachments) is 15 MB.
# Add Suppression
Source: https://docs.unosend.co/api-reference/suppressions/add-suppression
POST /suppressions
Manually add an email address to your suppression list.
## Request Body
Email address to suppress
Reason for suppression:
* `hard_bounce` - Invalid email address
* `spam_complaint` - Spam report
* `manual` - Manual suppression (default)
* `unsubscribe` - Unsubscribed
## Response
Unique suppression identifier
Suppressed email address (lowercase)
Reason for suppression
ISO 8601 timestamp
```bash cURL theme={null}
curl -X POST https://api.unosend.co/suppressions \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"email": "donotcontact@example.com",
"reason": "manual"
}'
```
```javascript Node.js theme={null}
const response = await fetch('https://api.unosend.co/suppressions', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_your_api_key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: 'donotcontact@example.com',
reason: 'manual'
})
});
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.post(
'https://api.unosend.co/suppressions',
headers={
'Authorization': 'Bearer un_your_api_key',
'Content-Type': 'application/json'
},
json={
'email': 'donotcontact@example.com',
'reason': 'manual'
}
)
data = response.json()
```
```json 201 Created theme={null}
{
"success": true,
"data": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"email": "donotcontact@example.com",
"reason": "manual",
"created_at": "2024-01-15T10:30:00.000Z"
}
}
```
If the email is already suppressed, the existing suppression will be updated with the new reason.
# Get Suppression
Source: https://docs.unosend.co/api-reference/suppressions/get-suppression
GET /suppressions/:id
Retrieve details of a specific suppression by ID.
## Path Parameters
The unique identifier of the suppression
## Response
Unique suppression identifier
Suppressed email address
Reason for suppression: `hard_bounce`, `spam_complaint`, `manual`, `unsubscribe`
ID of the email that caused automatic suppression (if applicable)
Additional information about the suppression, such as bounce type or diagnostic codes
ISO 8601 timestamp
```bash cURL theme={null}
curl https://api.unosend.co/suppressions/550e8400-e29b-41d4-a716-446655440000 \
-H "Authorization: Bearer un_your_api_key"
```
```javascript Node.js theme={null}
const response = await fetch(
'https://api.unosend.co/suppressions/550e8400-e29b-41d4-a716-446655440000',
{
headers: {
'Authorization': 'Bearer un_your_api_key'
}
}
);
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.unosend.co/suppressions/550e8400-e29b-41d4-a716-446655440000',
headers={'Authorization': 'Bearer un_your_api_key'}
)
data = response.json()
```
```json 200 OK theme={null}
{
"success": true,
"data": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"email": "bounced@example.com",
"reason": "hard_bounce",
"source_email_id": "email_abc123",
"metadata": {
"bounce_type": "Permanent",
"bounce_subtype": "NoEmail",
"diagnostic_code": "550 5.1.1 User unknown"
},
"created_at": "2024-01-15T10:30:00.000Z"
}
}
```
```json 404 Not Found theme={null}
{
"error": "Suppression not found"
}
```
# List Suppressions
Source: https://docs.unosend.co/api-reference/suppressions/list-suppressions
GET /suppressions
Retrieve a paginated list of suppressed email addresses.
## Query Parameters
Page number
Number of results per page (max 100)
Filter by suppression reason:
* `hard_bounce` - Invalid email addresses
* `spam_complaint` - Spam reports
* `manual` - Manually added
* `unsubscribe` - Unsubscribed recipients
## Response
Whether the request was successful
Unique suppression identifier
Suppressed email address
Reason for suppression
ID of the email that caused the suppression (if applicable)
Additional information about the suppression
ISO 8601 timestamp
Total number of suppressions
Current page number
Number of results per page
Total number of pages
```bash cURL theme={null}
curl "https://api.unosend.co/suppressions?page=1&per_page=10" \
-H "Authorization: Bearer un_your_api_key"
```
```javascript Node.js theme={null}
const response = await fetch('https://api.unosend.co/suppressions?page=1&per_page=10', {
headers: {
'Authorization': 'Bearer un_your_api_key'
}
});
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.unosend.co/suppressions',
params={'page': 1, 'per_page': 10},
headers={'Authorization': 'Bearer un_your_api_key'}
)
data = response.json()
```
```json 200 OK theme={null}
{
"success": true,
"data": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"email": "bounced@example.com",
"reason": "hard_bounce",
"source_email_id": "email_abc123",
"metadata": {
"bounce_type": "Permanent",
"bounce_subtype": "NoEmail"
},
"created_at": "2024-01-15T10:30:00.000Z"
}
],
"meta": {
"total": 42,
"page": 1,
"page_size": 10,
"pages": 5
}
}
```
# Remove Suppression
Source: https://docs.unosend.co/api-reference/suppressions/remove-suppression
DELETE /suppressions/:id
Remove an email from your suppression list by ID.
Be careful when removing hard bounce or spam complaint suppressions. Sending to these addresses again may harm your sender reputation and deliverability.
## Path Parameters
The unique identifier of the suppression to remove
## Response
```json 200 theme={null}
{
"success": true,
"data": {
"id": "550e8400-e29b-41d4-a716-446655440000"
}
}
```
```bash cURL theme={null}
curl -X DELETE https://api.unosend.co/suppressions/550e8400-e29b-41d4-a716-446655440000 \
-H "Authorization: Bearer un_your_api_key"
```
```javascript Node.js theme={null}
const response = await fetch(
'https://api.unosend.co/suppressions/550e8400-e29b-41d4-a716-446655440000',
{
method: 'DELETE',
headers: {
'Authorization': 'Bearer un_your_api_key'
}
}
);
```
```python Python theme={null}
import requests
response = requests.delete(
'https://api.unosend.co/suppressions/550e8400-e29b-41d4-a716-446655440000',
headers={'Authorization': 'Bearer un_your_api_key'}
)
```
```json 200 theme={null}
{
"success": true,
"data": {
"id": "550e8400-e29b-41d4-a716-446655440000"
}
}
```
```json 404 Not Found theme={null}
{
"error": "Suppression not found"
}
```
***
## Remove by Email
You can also remove a suppression by email address using a query parameter:
```bash theme={null}
DELETE /suppressions?email=bounced@example.com
```
```bash cURL (by email) theme={null}
curl -X DELETE "https://api.unosend.co/suppressions?email=bounced@example.com" \
-H "Authorization: Bearer un_your_api_key"
```
Removing a suppression allows you to send emails to that address again. The email may get re-suppressed if it bounces or receives a complaint.
# Create Template
Source: https://docs.unosend.co/api-reference/templates/create-template
POST /templates
Create a new email template.
A friendly name for the template.
The email subject line. Supports variables like `{{variable}}`.
The HTML body of the email. Supports variables.
The plain text body of the email. Supports variables.
### Request
```bash cURL theme={null}
curl -X POST https://api.unosend.co/templates \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"name": "Welcome Email",
"subject": "Welcome to {{company_name}}, {{first_name}}!",
"html": "Welcome, {{first_name}}!
Thanks for joining {{company_name}}.
"
}'
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/templates', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_xxxxxxxxxx',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Welcome Email',
subject: 'Welcome to {{company_name}}, {{first_name}}!',
html: 'Welcome, {{first_name}}!
Thanks for joining {{company_name}}.
'
})
});
```
```python Python theme={null}
import requests
requests.post('https://api.unosend.co/templates',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'},
json={
'name': 'Welcome Email',
'subject': 'Welcome to {{company_name}}, {{first_name}}!',
'html': 'Welcome, {{first_name}}!
Thanks for joining {{company_name}}.
'
}
)
```
### Response
```json 201 theme={null}
{
"success": true,
"data": {
"id": "tpl_abc123",
"name": "Welcome Email",
"subject": "Welcome to {{company_name}}, {{first_name}}!",
"html": "Welcome, {{first_name}}!
Thanks for joining {{company_name}}.
",
"created_at": "2024-01-15T10:30:00.000Z"
}
}
```
# Delete Template
Source: https://docs.unosend.co/api-reference/templates/delete-template
DELETE /templates/{id}
Delete a template.
The ID of the template to delete.
### Request
```bash cURL theme={null}
curl -X DELETE https://api.unosend.co/templates/tpl_abc123 \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/templates/tpl_abc123', {
method: 'DELETE',
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
```
```python Python theme={null}
import requests
requests.delete('https://api.unosend.co/templates/tpl_abc123',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'}
)
```
### Response
```json 200 theme={null}
{
"success": true,
"data": {
"id": "tpl_abc123"
}
}
```
# Retrieve Template
Source: https://docs.unosend.co/api-reference/templates/get-template
GET /templates/{id}
Retrieve a template by ID.
The ID of the template.
### Request
```bash cURL theme={null}
curl https://api.unosend.co/templates/tpl_abc123 \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/templates/tpl_abc123', {
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
```
```python Python theme={null}
import requests
requests.get('https://api.unosend.co/templates/tpl_abc123',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'}
)
```
### Response
```json 200 theme={null}
{
"success": true,
"data": {
"id": "tpl_abc123",
"name": "Welcome Email",
"subject": "Welcome to {{company_name}}, {{first_name}}!",
"html": "Welcome, {{first_name}}!
Thanks for joining {{company_name}}.
",
"created_at": "2024-01-15T10:30:00.000Z"
}
}
```
# List Templates
Source: https://docs.unosend.co/api-reference/templates/list-templates
GET /templates
List all templates in your account.
### Request
```bash cURL theme={null}
curl https://api.unosend.co/templates \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/templates', {
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
```
```python Python theme={null}
import requests
requests.get('https://api.unosend.co/templates',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'}
)
```
### Response
```json 200 theme={null}
{
"success": true,
"data": [
{
"id": "tpl_abc123",
"name": "Welcome Email",
"subject": "Welcome to {{company_name}}, {{first_name}}!",
"created_at": "2024-01-15T10:30:00.000Z"
},
{
"id": "tpl_def456",
"name": "Password Reset",
"subject": "Reset your password",
"created_at": "2024-01-14T08:00:00.000Z"
}
]
}
```
# Update Template
Source: https://docs.unosend.co/api-reference/templates/update-template
PATCH /templates/{id}
Update a template's content.
The ID of the template.
A new name for the template.
A new subject line.
New HTML body content.
New plain text body content.
### Request
```bash cURL theme={null}
curl -X PATCH https://api.unosend.co/templates/tpl_abc123 \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"subject": "Welcome aboard, {{first_name}}!"
}'
```
### Response
```json 200 theme={null}
{
"success": true,
"data": {
"id": "tpl_abc123",
"name": "Welcome Email",
"subject": "Welcome aboard, {{first_name}}!",
"html": "Welcome, {{first_name}}!
Thanks for joining {{company_name}}.
"
}
}
```
# Create Webhook
Source: https://docs.unosend.co/api-reference/webhooks/create-webhook
POST /webhooks
Create a new webhook endpoint.
The URL to receive webhook events.
Events to subscribe to: `email.sent`, `email.delivered`, `email.opened`, `email.clicked`, `email.bounced`, `email.complained`.
### Request
```bash cURL theme={null}
curl -X POST https://api.unosend.co/webhooks \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"url": "https://yourapp.com/webhooks/unosend",
"events": ["email.delivered", "email.bounced"]
}'
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/webhooks', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_xxxxxxxxxx',
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: 'https://yourapp.com/webhooks/unosend',
events: ['email.delivered', 'email.bounced']
})
});
```
```python Python theme={null}
import requests
requests.post('https://api.unosend.co/webhooks',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'},
json={
'url': 'https://yourapp.com/webhooks/unosend',
'events': ['email.delivered', 'email.bounced']
}
)
```
### Response
```json 201 theme={null}
{
"success": true,
"data": {
"id": "wh_123",
"url": "https://yourapp.com/webhooks/unosend",
"events": ["email.delivered", "email.bounced"],
"signing_secret": "whsec_abc123...",
"created_at": "2024-01-15T10:30:00.000Z"
}
}
```
Store the `signing_secret` securely. It's only shown once and is used to verify webhook signatures.
# Delete Webhook
Source: https://docs.unosend.co/api-reference/webhooks/delete-webhook
DELETE /webhooks/{id}
Delete a webhook endpoint.
The ID of the webhook to delete.
### Request
```bash cURL theme={null}
curl -X DELETE https://api.unosend.co/webhooks/wh_123 \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/webhooks/wh_123', {
method: 'DELETE',
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
```
```python Python theme={null}
import requests
requests.delete('https://api.unosend.co/webhooks/wh_123',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'}
)
```
### Response
```json 200 theme={null}
{
"success": true,
"data": {
"id": "wh_123"
}
}
```
# Retrieve Webhook
Source: https://docs.unosend.co/api-reference/webhooks/get-webhook
GET /webhooks/{id}
Retrieve a webhook by ID.
The ID of the webhook.
### Request
```bash cURL theme={null}
curl https://api.unosend.co/webhooks/wh_123 \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/webhooks/wh_123', {
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
```
```python Python theme={null}
import requests
requests.get('https://api.unosend.co/webhooks/wh_123',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'}
)
```
### Response
```json 200 theme={null}
{
"success": true,
"data": {
"id": "wh_123",
"url": "https://yourapp.com/webhooks/unosend",
"events": ["email.delivered", "email.bounced"],
"created_at": "2024-01-15T10:30:00.000Z"
}
}
```
# List Webhooks
Source: https://docs.unosend.co/api-reference/webhooks/list-webhooks
GET /webhooks
List all webhooks in your account.
### Request
```bash cURL theme={null}
curl https://api.unosend.co/webhooks \
-H "Authorization: Bearer un_xxxxxxxxxx"
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/webhooks', {
headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' }
});
```
```python Python theme={null}
import requests
requests.get('https://api.unosend.co/webhooks',
headers={'Authorization': 'Bearer un_xxxxxxxxxx'}
)
```
### Response
```json 200 theme={null}
{
"success": true,
"data": [
{
"id": "wh_123",
"url": "https://yourapp.com/webhooks/unosend",
"events": ["email.delivered", "email.bounced"],
"created_at": "2024-01-15T10:30:00.000Z"
}
]
}
```
# Update Webhook
Source: https://docs.unosend.co/api-reference/webhooks/update-webhook
PATCH /webhooks/{id}
Update a webhook's URL or events.
The ID of the webhook.
The new URL to receive webhook events.
New list of events to subscribe to.
### Request
```bash cURL theme={null}
curl -X PATCH https://api.unosend.co/webhooks/wh_123 \
-H "Authorization: Bearer un_xxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"events": ["email.delivered", "email.bounced", "email.opened"]
}'
```
### Response
```json 200 theme={null}
{
"success": true,
"data": {
"id": "wh_123",
"url": "https://yourapp.com/webhooks/unosend",
"events": ["email.delivered", "email.bounced", "email.opened"]
}
}
```
# Authentication
Source: https://docs.unosend.co/authentication
Authenticate API requests using Bearer tokens.
All API requests require a Bearer token in the `Authorization` header.
```text theme={null}
Authorization: Bearer un_your_api_key
```
## Getting Your Send Mail Token
Your Send Mail Token is provided when you're onboarded. Each token is unique to your account. If you need a new token, [contact us](https://unosend.co/contact).
Keep your token secure. Never expose it in client-side code.
## Using the Key
Include it in every request:
```bash theme={null}
curl -X POST https://api.unosend.co/emails \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{"from": "hi@yourdomain.com", "to": ["user@example.com"], "subject": "Test", "html": "Hello
"}'
```
## Security Best Practices
* **Never expose keys in client-side code** — only use them server-side
* **Use environment variables** — store keys in `UNOSEND_API_KEY`, not in source code
* **Rotate keys regularly** — contact us if you need to regenerate your token
* **One key per service** — request separate tokens for different apps so you can revoke independently
## Error Responses
| Status | Meaning |
| ------ | ------------------------------------------- |
| `401` | Missing or invalid API key |
| `403` | Key doesn't have permission for this action |
# Changelog
Source: https://docs.unosend.co/changelog
Track all updates and improvements to the Unosend API.
Follow [@unosendco](https://x.com/unosendco) to stay updated on new features.
## May 2026
**May 16, 2026** - Platform Launch
* **REST API** — Send transactional emails via `api.unosend.co`
* **SMTP Relay** — Connect via `smtp.unosend.co:587` with TLS
* **Email Templates** — Create and send with dynamic merge tags
* **Domain Authentication** — SPF, DKIM, and CNAME tracking verification
* **Webhooks** — Real-time delivery, bounce, open, and click notifications
* **Suppression Lists** — Automatic bounce/complaint handling
* **Email Logs** — Full delivery history with export capability
* **File Cache** — Upload and reuse attachments across emails
* **Batch Sending** — Send to multiple recipients in one API call
* **Open & Click Tracking** — Built-in tracking with per-email control
* **Dedicated IP** — Available for high-volume senders
# Domain Verification
Source: https://docs.unosend.co/guides/domain-verification
Learn how to verify your sending domain for better email deliverability. Domain verification enables DKIM signing and improves inbox placement.
## Why Verify Your Domain?
All plans include **unlimited domains** — add as many sending domains as you need at no extra cost.
DKIM signing proves email authenticity
Send from your own domain address
Recipients see your domain, not ours
Avoid "via unosend.co" labels
## Setup Guide
Add your domain to Unosend through the dashboard or API:
```bash cURL theme={null}
curl -X POST https://api.unosend.co/domains \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"domain": "yourdomain.com"
}'
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/domains', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_your_api_key',
'Content-Type': 'application/json'
},
body: JSON.stringify({ domain: 'yourdomain.com' })
});
```
```python Python theme={null}
import requests
requests.post('https://api.unosend.co/domains',
headers={'Authorization': 'Bearer un_your_api_key'},
json={'domain': 'yourdomain.com'}
)
```
### Response
```json response.json theme={null}
{
"id": "dom_xxxxxxxxxxxxxxxx",
"domain": "yourdomain.com",
"status": "pending",
"dns_records": [
{
"type": "TXT",
"name": "xxxxxxxx._domainkey.yourdomain.com",
"value": "k=rsa; p=MIGfMA0GCSqGSIb3..."
},
{
"type": "CNAME",
"name": "bounce-mail.yourdomain.com",
"value": "cname.unosend.co"
}
],
"created_at": "2024-01-15T10:30:00Z"
}
```
Add the following **2 DNS records** to your domain. Go to your DNS provider (Cloudflare, Route53, GoDaddy, etc.) and add these records:
### 1. DKIM Record (TXT)
Authenticates your emails with a DKIM signature:
| Field | Value |
| --------- | ----------------------------------------------------- |
| Type | `TXT` |
| Name/Host | `xxxxxxxx._domainkey` (provided in response) |
| Value | `k=rsa; p=MIGfMA0GCSqGSIb3...` (provided in response) |
| TTL | 3600 (or Auto) |
The DKIM record name and value are unique to your domain. Copy them exactly from the API response or dashboard.
### 2. CNAME Record (Bounce Handling)
This enables bounce handling through Unosend's infrastructure:
| Field | Value |
| --------- | ------------------ |
| Type | `CNAME` |
| Name/Host | `bounce-mail` |
| Value | `cname.unosend.co` |
| TTL | 3600 (or Auto) |
**Just 2 records!** A DKIM TXT record and a CNAME for bounce handling. That's all you need.
After adding DNS records, trigger verification. DNS propagation can take up to 48 hours, but usually completes within a few minutes.
```bash cURL theme={null}
curl -X POST https://api.unosend.co/domains/dom_xxxxxxxx/verify \
-H "Authorization: Bearer un_your_api_key"
```
### Response
```json response.json theme={null}
{
"id": "dom_xxxxxxxxxxxxxxxx",
"domain": "yourdomain.com",
"status": "verified",
"verified_at": "2024-01-15T10:35:00Z"
}
```
## DNS Record Summary
Here's a quick reference for all required records:
| Type | Name | Value |
| ----- | --------------------- | ---------------------------------- |
| TXT | `xxxxxxxx._domainkey` | `k=rsa; p=...` (unique per domain) |
| CNAME | `bounce-mail` | `cname.unosend.co` |
## Provider-Specific Instructions
1. Go to your domain in Cloudflare dashboard
2. Click **DNS** in the sidebar
3. Click **Add record** for each record:
* For TXT: Select TXT, enter the `_domainkey` name and DKIM value
* For CNAME: Select CNAME, enter `bounce-mail` as name, `cname.unosend.co` as value
4. Set proxy status to **DNS only** (gray cloud) for the CNAME record
1. Open Route 53 console
2. Select your hosted zone
3. Click **Create record** for each entry:
* TXT record: Simple routing, enter `_domainkey` name and value in quotes
* CNAME record: Simple routing, enter `bounce-mail` as name, `cname.unosend.co` as value
1. Go to your domain's DNS Management
2. Click **Add** in the Records section
3. For TXT record:
* Type: TXT
* Name: the `_domainkey` value
* Value: the DKIM key
4. For CNAME record:
* Type: CNAME
* Name: `bounce-mail`
* Value: `cname.unosend.co`
1. Go to Domain List → Manage → Advanced DNS
2. Click **Add New Record** for each entry
3. For TXT record: Select TXT Record, enter `_domainkey` name and value
4. For CNAME record: Select CNAME Record, enter `bounce-mail` and target
1. Go to DNS settings for your domain
2. Click **Manage custom records**
3. Add each record with the correct type and values
## Verification Complete!
Once verified, you can start sending emails from your domain. Your emails will be:
* **DKIM-signed** with your unique key
* **Delivered via Unosend's dedicated infrastructure** for maximum deliverability
* **Bounce-tracked** automatically
## Sending Emails
After verification, send emails from any address at your domain:
```bash theme={null}
curl -X POST https://api.unosend.co/emails \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"from": "hello@yourdomain.com",
"to": "recipient@example.com",
"subject": "Hello from my verified domain!",
"html": "This email is DKIM-signed and delivered via Unosend.
"
}'
```
# Sending Emails
Source: https://docs.unosend.co/guides/sending-emails
Learn how to send different types of emails with Unosend, from simple messages to complex HTML emails with attachments.
## Sending a Basic Email
The simplest way to send an email with Unosend. **Works with any programming language!**
```bash cURL theme={null}
curl -X POST https://api.unosend.co/emails \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"from": "hello@yourdomain.com",
"to": ["user@example.com"],
"subject": "Hello from Unosend!",
"html": "Hello World
This is a test email.
"
}'
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/emails', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_your_api_key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: 'hello@yourdomain.com',
to: ['user@example.com'],
subject: 'Hello from Unosend!',
html: 'Hello World
This is a test email.
'
})
});
```
```python Python theme={null}
import requests
requests.post('https://api.unosend.co/emails',
headers={'Authorization': 'Bearer un_your_api_key'},
json={
'from': 'hello@yourdomain.com',
'to': ['user@example.com'],
'subject': 'Hello from Unosend!',
'html': 'Hello World
This is a test email.
'
}
)
```
```php PHP theme={null}
$ch = curl_init('https://api.unosend.co/emails');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer un_your_api_key', 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'from' => 'hello@yourdomain.com',
'to' => ['user@example.com'],
'subject' => 'Hello from Unosend!',
'html' => 'Hello World
This is a test email.
'
])
]);
curl_exec($ch);
```
### Response
```json response.json theme={null}
{
"id": "eml_xxxxxxxxxxxxxxxx",
"from": "hello@yourdomain.com",
"to": ["user@example.com"],
"subject": "Hello from Unosend!",
"status": "queued",
"created_at": "2024-01-15T10:30:00Z"
}
```
## Email Options
Send copies to additional recipients
Include files with your emails
Set a different reply address
```bash cURL theme={null}
curl -X POST https://api.unosend.co/emails \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"from": "John Doe ",
"to": ["user@example.com"],
"subject": "Welcome to Our Platform",
"html": "Welcome!
Thanks for joining us.
",
"text": "Welcome! Thanks for joining us.",
"cc": ["manager@yourdomain.com"],
"bcc": ["archive@yourdomain.com"],
"reply_to": "support@yourdomain.com",
"headers": {
"X-Custom-Header": "custom-value"
},
"tags": {
"campaign": "onboarding",
"user_type": "new"
}
}'
```
## Sender Name Formats
You can specify the sender name in different ways:
```text sender-formats.txt theme={null}
// Email only
"from": "hello@yourdomain.com"
// Name and email
"from": "John Doe "
// Company name
"from": "Acme Inc "
// No-reply address
"from": "Acme Inc "
```
## Sending to Multiple Recipients
Send the same email to multiple recipients:
```bash cURL theme={null}
curl -X POST https://api.unosend.co/emails \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"from": "hello@yourdomain.com",
"to": [
"user1@example.com",
"user2@example.com",
"user3@example.com"
],
"subject": "Team Update",
"html": "Hi team, here is an update...
"
}'
```
All recipients will see each other's addresses. For private sends, use BCC or send individual emails.
## Sending Attachments
Attach files to your emails using base64 encoding:
```bash cURL theme={null}
curl -X POST https://api.unosend.co/emails \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"from": "billing@yourdomain.com",
"to": ["customer@example.com"],
"subject": "Your Monthly Report",
"html": "Please find your monthly report attached.
",
"attachments": [
{
"filename": "report.pdf",
"content": "base64_encoded_content_here",
"content_type": "application/pdf"
},
{
"filename": "data.csv",
"content": "base64_encoded_content_here",
"content_type": "text/csv"
}
]
}'
```
### Node.js Example
```javascript attachments.js theme={null}
import fs from 'fs';
// Read and encode file
const pdfBuffer = fs.readFileSync('report.pdf');
const base64Content = pdfBuffer.toString('base64');
const response = await fetch('https://api.unosend.co/emails', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_your_api_key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: 'billing@yourdomain.com',
to: ['customer@example.com'],
subject: 'Your Monthly Report',
html: 'Please find your monthly report attached.
',
attachments: [
{
filename: 'report.pdf',
content: base64Content,
content_type: 'application/pdf'
}
]
})
});
```
### Supported Content Types
* `application/pdf`
* `image/png`
* `image/jpeg`
* `text/csv`
* `text/plain`
* `application/zip`
* `application/json`
* `text/html`
## Rich HTML Emails
Create beautiful HTML emails with styling:
```html html-email.html theme={null}
Welcome to Unosend!
Hi {{name}},
Thanks for signing up. Here's what you can do next:
- Complete your profile
- Explore our features
- Send your first email
Go to Dashboard
© 2024 Your Company. All rights reserved.
```
**Best Practice:** Always include a plain text version (`text`) for email clients that don't support HTML.
## Error Handling
Common error codes and how to handle them:
| Code | Description | Action |
| --------------------- | --------------------------- | ------------------------ |
| `validation_error` | Invalid request parameters | Check your request body |
| `domain_not_verified` | Sending domain not verified | Verify your domain first |
| `rate_limit_exceeded` | Too many requests | Wait and retry |
| `insufficient_quota` | Monthly limit reached | Upgrade your plan |
```json error-response.json theme={null}
{
"error": {
"code": "domain_not_verified",
"message": "The domain 'example.com' is not verified. Please verify your domain before sending."
}
}
```
## Best Practices
Always verify your sending domain for better deliverability
Include both HTML and plain text versions of your email
Use inline CSS for HTML emails (external stylesheets often don't work)
Keep attachment sizes under 10MB for best delivery
Use tags to track email campaigns and analyze performance
# SMTP Integration
Source: https://docs.unosend.co/guides/smtp
Learn how to send emails using SMTP with Unosend. Connect your existing tools like Laravel, WordPress, Supabase, Django, and more.
Send emails using SMTP without the need for any external libraries or dependencies. Connect seamlessly with your existing tools and frameworks.
## SMTP Credentials
Use these credentials to connect any SMTP-compatible application to Unosend:
You can find your SMTP credentials in [Settings → SMTP](/settings?tab=smtp) or create a new API key in [API Keys](/api-keys).
## Connection Security
Upgrades the connection to secure. Works with most email clients and services like Supabase.
`Port 587`
Immediately connects via SSL/TLS. Use when your client requires implicit TLS.
`Port 465`
## Quick Start Examples
```javascript Nodemailer (Node.js) theme={null}
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
host: 'smtp.unosend.co',
port: 587,
secure: false, // true for 465, false for 587
auth: {
user: 'emailapikey',
pass: 'un_your_api_key', // Your API key
},
});
async function sendEmail() {
const info = await transporter.sendMail({
from: 'hello@yourdomain.com',
to: 'user@example.com',
subject: 'Hello from Unosend!',
html: 'It works!
',
});
console.log('Message sent:', info.messageId);
}
sendEmail();
```
```python Python (smtplib) theme={null}
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
smtp_host = "smtp.unosend.co"
smtp_port = 587
smtp_user = "emailapikey"
smtp_pass = "un_your_api_key" # Your API key
msg = MIMEMultipart()
msg['From'] = 'hello@yourdomain.com'
msg['To'] = 'user@example.com'
msg['Subject'] = 'Hello from Unosend!'
body = 'It works!
'
msg.attach(MIMEText(body, 'html'))
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.starttls()
server.login(smtp_user, smtp_pass)
server.send_message(msg)
print('Email sent successfully!')
```
```env Laravel (.env) theme={null}
MAIL_MAILER=smtp
MAIL_HOST=smtp.unosend.co
MAIL_PORT=587
MAIL_USERNAME=emailapikey
MAIL_PASSWORD=un_your_api_key
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=hello@yourdomain.com
MAIL_FROM_NAME="${APP_NAME}"
```
```python Django (settings.py) theme={null}
# Email configuration
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.unosend.co'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'emailapikey'
EMAIL_HOST_PASSWORD = 'un_your_api_key'
DEFAULT_FROM_EMAIL = 'hello@yourdomain.com'
```
```ruby Ruby on Rails theme={null}
# config/environments/production.rb
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.unosend.co',
port: 587,
user_name: 'emailapikey',
password: 'un_your_api_key',
authentication: :plain,
enable_starttls_auto: true
}
```
```text Supabase theme={null}
Host: smtp.unosend.co
Port: 587
Username: emailapikey
Password: un_your_api_key
Sender email: hello@yourdomain.com
```
## Email Tracking via SMTP
Track opens and clicks for emails sent via SMTP using custom headers. Add these headers to your email message to enable tracking:
| Header | Values | Description |
| ------------------------ | ------------- | ---------------------------------------------------- |
| `X-Unosend-Track-Opens` | `true` or `1` | Injects a tracking pixel to detect email opens |
| `X-Unosend-Track-Clicks` | `true` or `1` | Rewrites links to track clicks |
| `X-Unosend-Tags` | `tag1,tag2` | Add custom tags for categorization (comma-separated) |
Tracking headers are automatically removed before the email is delivered, so recipients won't see them.
### Examples with Tracking
```javascript Nodemailer (Node.js) theme={null}
const info = await transporter.sendMail({
from: 'hello@yourdomain.com',
to: 'user@example.com',
subject: 'Newsletter',
html: 'Hello!
Click here
',
headers: {
'X-Unosend-Track-Opens': 'true',
'X-Unosend-Track-Clicks': 'true',
'X-Unosend-Tags': 'newsletter,january'
}
});
```
```python Python (smtplib) theme={null}
msg = MIMEMultipart()
msg['From'] = 'hello@yourdomain.com'
msg['To'] = 'user@example.com'
msg['Subject'] = 'Newsletter'
msg['X-Unosend-Track-Opens'] = 'true'
msg['X-Unosend-Track-Clicks'] = 'true'
msg['X-Unosend-Tags'] = 'newsletter,january'
body = 'Hello!
Click here
'
msg.attach(MIMEText(body, 'html'))
```
```php Laravel theme={null}
use Illuminate\Support\Facades\Mail;
use Illuminate\Mail\Message;
Mail::send([], [], function (Message $message) {
$message->to('user@example.com')
->subject('Newsletter')
->html('Hello!
')
->getHeaders()
->addTextHeader('X-Unosend-Track-Opens', 'true')
->addTextHeader('X-Unosend-Track-Clicks', 'true');
});
```
```ruby Ruby on Rails theme={null}
class NewsletterMailer < ApplicationMailer
def welcome_email(user)
headers['X-Unosend-Track-Opens'] = 'true'
headers['X-Unosend-Track-Clicks'] = 'true'
headers['X-Unosend-Tags'] = 'newsletter,welcome'
mail(to: user.email, subject: 'Welcome!')
end
end
```
View open and click events in your [Analytics dashboard](/analytics) or receive them via [Webhooks](/webhooks).
## Supported Integrations
Unosend SMTP works with any application that supports SMTP:
## Next Steps
Verify your domain for better deliverability
Learn about advanced email options
# Email Templates
Source: https://docs.unosend.co/guides/templates
Learn how to create and use reusable email templates with dynamic variables for personalized email content.
## Why Use Templates?
* **Consistency** - Maintain brand consistency across all emails
* **Efficiency** - Write once, use many times
* **Personalization** - Dynamic variables for each recipient
* **Easy Updates** - Change template once, affects all future emails
## Creating a Template
Create a template with dynamic variables using double curly braces:
```bash cURL theme={null}
curl -X POST https://api.unosend.co/templates \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"name": "Welcome Email",
"subject": "Welcome to {{company_name}}, {{first_name}}!",
"html": "Welcome, {{first_name}}!
Thanks for joining {{company_name}}.
Go to Dashboard",
"text": "Welcome, {{first_name}}! Thanks for joining {{company_name}}. Visit: {{dashboard_url}}"
}'
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/templates', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_your_api_key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Welcome Email',
subject: 'Welcome to {{company_name}}, {{first_name}}!',
html: 'Welcome, {{first_name}}!
Thanks for joining {{company_name}}.
Go to Dashboard',
text: 'Welcome, {{first_name}}! Thanks for joining {{company_name}}. Visit: {{dashboard_url}}'
})
});
```
```python Python theme={null}
import requests
requests.post('https://api.unosend.co/templates',
headers={'Authorization': 'Bearer un_your_api_key'},
json={
'name': 'Welcome Email',
'subject': 'Welcome to {{company_name}}, {{first_name}}!',
'html': 'Welcome, {{first_name}}!
Thanks for joining {{company_name}}.
Go to Dashboard',
'text': 'Welcome, {{first_name}}! Thanks for joining {{company_name}}. Visit: {{dashboard_url}}'
}
)
```
### Response
```json response.json theme={null}
{
"id": "tpl_xxxxxxxxxxxxxxxx",
"name": "Welcome Email",
"subject": "Welcome to {{company_name}}, {{first_name}}!",
"variables": ["company_name", "first_name", "dashboard_url"],
"created_at": "2024-01-15T10:30:00Z"
}
```
## Variable Syntax
Templates support various variable features:
### Basic Variables
```html basic-variables.html theme={null}
Hello, {{first_name}}!
Your email is: {{email}}
```
### Default Values
```html default-values.html theme={null}
Hello, {{first_name | default: "there"}}!
Your plan: {{plan | default: "Free"}}
```
### Conditional Content
```html conditionals.html theme={null}
{{#if is_premium}}
Premium Member
{{/if}}
{{#if has_items}}
Your Items
{{else}}
No items yet. Start shopping!
{{/if}}
```
### Loops
```html loops.html theme={null}
Your Order
{{#each items}}
| {{name}} |
{{quantity}} |
{{price}} |
{{/each}}
Total: {{total}}
```
## Sending Emails with Templates
Use `template_id` instead of `html` when sending:
```bash cURL theme={null}
curl -X POST https://api.unosend.co/emails \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"from": "hello@yourdomain.com",
"to": ["john@example.com"],
"template_id": "tpl_xxxxxxxxxxxxxxxx",
"variables": {
"first_name": "John",
"company_name": "Acme Inc",
"dashboard_url": "https://app.acme.com/dashboard",
"is_premium": true
}
}'
```
## Batch Sending with Templates
Send personalized emails to multiple recipients efficiently using the batch endpoint:
```bash cURL theme={null}
curl -X POST https://api.unosend.co/emails/batch \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"emails": [
{
"from": "hello@yourdomain.com",
"to": ["john@example.com"],
"template_id": "tpl_xxxxxxxxxxxxxxxx",
"variables": {
"first_name": "John",
"plan": "Pro"
}
},
{
"from": "hello@yourdomain.com",
"to": ["jane@example.com"],
"template_id": "tpl_xxxxxxxxxxxxxxxx",
"variables": {
"first_name": "Jane",
"plan": "Free"
}
}
]
}'
```
## Common Template Examples
### Order Confirmation
```html order-confirmation.html theme={null}
Order Confirmed!
Hi {{customer_name}},
Thanks for your order #{{order_number}}.
Order Details
| Item |
Qty |
Price |
{{#each items}}
| {{name}} |
{{quantity}} |
{{price}} |
{{/each}}
Total: {{total}}
Shipping to: {{shipping_address}}
```
### Password Reset
```html password-reset.html theme={null}
Reset Your Password
Hi {{first_name | default: "there"}},
We received a request to reset your password.
Reset Password
This link will expire in {{expiry_hours}} hours.
If you didn't request this, please ignore this email.
```
## Managing Templates
### Update a Template
```bash cURL theme={null}
curl -X PATCH https://api.unosend.co/templates/tpl_xxxxxxxx \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"subject": "Welcome aboard, {{first_name}}!",
"html": "Updated welcome content
"
}'
```
### List Templates
```bash cURL theme={null}
curl https://api.unosend.co/templates \
-H "Authorization: Bearer un_your_api_key"
```
### Get a Template
```bash cURL theme={null}
curl https://api.unosend.co/templates/tpl_xxxxxxxx \
-H "Authorization: Bearer un_your_api_key"
```
### Delete a Template
```bash cURL theme={null}
curl -X DELETE https://api.unosend.co/templates/tpl_xxxxxxxx \
-H "Authorization: Bearer un_your_api_key"
```
# Webhooks
Source: https://docs.unosend.co/guides/webhooks
Receive real-time notifications about email events like deliveries, opens, clicks, and bounces via HTTP webhooks.
## How Webhooks Work
Email is delivered, opened, clicked, etc.
HTTP POST to your endpoint
Validate signature for security
Update your database, trigger actions
## Event Types
| Event | Description |
| ------------------ | ---------------------------------------- |
| `email.sent` | Email was sent to recipient |
| `email.delivered` | Email was delivered to recipient's inbox |
| `email.opened` | Recipient opened the email |
| `email.clicked` | Recipient clicked a link in the email |
| `email.bounced` | Email bounced (hard or soft) |
| `email.complained` | Recipient marked as spam |
## Creating a Webhook
Create a webhook endpoint to receive events:
```bash cURL theme={null}
curl -X POST https://api.unosend.co/webhooks \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"url": "https://yourapp.com/api/webhooks/unosend",
"events": [
"email.delivered",
"email.opened",
"email.clicked",
"email.bounced",
"email.complained"
]
}'
```
```javascript JavaScript theme={null}
await fetch('https://api.unosend.co/webhooks', {
method: 'POST',
headers: {
'Authorization': 'Bearer un_your_api_key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: 'https://yourapp.com/api/webhooks/unosend',
events: ['email.delivered', 'email.opened', 'email.clicked', 'email.bounced', 'email.complained']
})
});
```
```python Python theme={null}
import requests
requests.post('https://api.unosend.co/webhooks',
headers={'Authorization': 'Bearer un_your_api_key'},
json={
'url': 'https://yourapp.com/api/webhooks/unosend',
'events': ['email.delivered', 'email.opened', 'email.clicked', 'email.bounced', 'email.complained']
}
)
```
### Response
```json response.json theme={null}
{
"id": "whk_xxxxxxxxxxxxxxxx",
"url": "https://yourapp.com/api/webhooks/unosend",
"events": [
"email.delivered",
"email.opened",
"email.clicked",
"email.bounced",
"email.complained"
],
"signing_secret": "whsec_xxxxxxxxxxxxxxxxxxxxxxxx",
"created_at": "2024-01-15T10:30:00Z"
}
```
Store the `signing_secret` securely - you'll need it to verify webhooks.
## Webhook Payload
Each webhook request includes the following structure:
```json webhook-payload.json theme={null}
{
"id": "evt_xxxxxxxxxxxxxxxx",
"type": "email.delivered",
"created_at": "2024-01-15T10:30:00Z",
"data": {
"email_id": "eml_xxxxxxxxxxxxxxxx",
"from": "hello@yourdomain.com",
"to": "user@example.com",
"subject": "Welcome to Our Platform",
"tags": {
"campaign": "onboarding"
}
}
}
```
### Click Event Example
```json click-event.json theme={null}
{
"id": "evt_xxxxxxxxxxxxxxxx",
"type": "email.clicked",
"created_at": "2024-01-15T11:45:00Z",
"data": {
"email_id": "eml_xxxxxxxxxxxxxxxx",
"to": "user@example.com",
"link": "https://yourdomain.com/pricing",
"user_agent": "Mozilla/5.0...",
"ip_address": "192.168.1.1"
}
}
```
### Bounce Event Example
```json bounce-event.json theme={null}
{
"id": "evt_xxxxxxxxxxxxxxxx",
"type": "email.bounced",
"created_at": "2024-01-15T10:32:00Z",
"data": {
"email_id": "eml_xxxxxxxxxxxxxxxx",
"to": "invalid@example.com",
"bounce_type": "hard",
"bounce_reason": "User unknown"
}
}
```
## Verifying Webhook Signatures
Always verify webhook signatures to ensure requests are from Unosend.
Each webhook request includes a signature in the `X-Unosend-Signature` header:
```typescript verify-webhook.ts theme={null}
import crypto from 'crypto';
function verifyWebhookSignature(
payload: string,
signature: string,
secret: string
): boolean {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(`sha256=${expectedSignature}`)
);
}
```
## Complete Webhook Handler
```typescript Next.js App Router theme={null}
// app/api/webhooks/unosend/route.ts
import { NextResponse } from 'next/server';
import crypto from 'crypto';
function verifySignature(payload: string, signature: string): boolean {
const secret = process.env.UNOSEND_WEBHOOK_SECRET!;
const expected = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return signature === `sha256=${expected}`;
}
export async function POST(request: Request) {
const payload = await request.text();
const signature = request.headers.get('X-Unosend-Signature');
if (!signature || !verifySignature(payload, signature)) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
}
const event = JSON.parse(payload);
switch (event.type) {
case 'email.delivered':
console.log('Email delivered:', event.data.email_id);
// Update email status in database
break;
case 'email.opened':
console.log('Email opened:', event.data.email_id);
// Track email open
break;
case 'email.clicked':
console.log('Link clicked:', event.data.link);
// Track link click
break;
case 'email.bounced':
console.log('Email bounced:', event.data.to);
// Mark contact as bounced
break;
case 'email.complained':
console.log('Spam complaint:', event.data.to);
// Unsubscribe user
break;
default:
console.log('Unhandled event type:', event.type);
}
return NextResponse.json({ received: true });
}
```
```python Python Flask theme={null}
import hmac
import hashlib
from flask import Flask, request, jsonify
app = Flask(__name__)
WEBHOOK_SECRET = 'whsec_your_secret'
def verify_signature(payload: bytes, signature: str) -> bool:
expected = hmac.new(
WEBHOOK_SECRET.encode(),
payload,
hashlib.sha256
).hexdigest()
return signature == f'sha256={expected}'
@app.route('/api/webhooks/unosend', methods=['POST'])
def handle_webhook():
payload = request.get_data()
signature = request.headers.get('X-Unosend-Signature')
if not signature or not verify_signature(payload, signature):
return jsonify({'error': 'Invalid signature'}), 401
event = request.get_json()
if event['type'] == 'email.delivered':
print(f"Email delivered: {event['data']['email_id']}")
elif event['type'] == 'email.bounced':
print(f"Email bounced: {event['data']['to']}")
return jsonify({'received': True})
```
## Retry Logic
If your endpoint returns a non-2xx status code, we'll retry the webhook:
* 1st retry: 1 minute after failure
* 2nd retry: 5 minutes after failure
* 3rd retry: 30 minutes after failure
* 4th retry: 2 hours after failure
* 5th retry: 8 hours after failure
After 5 failed attempts, the webhook is marked as failed and won't be retried.
## Managing Webhooks
### List Webhooks
```bash cURL theme={null}
curl https://api.unosend.co/webhooks \
-H "Authorization: Bearer un_your_api_key"
```
### Update a Webhook
```bash cURL theme={null}
curl -X PATCH https://api.unosend.co/webhooks/whk_xxxxxxxx \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"events": ["email.delivered", "email.bounced"]
}'
```
### Delete a Webhook
```bash cURL theme={null}
curl -X DELETE https://api.unosend.co/webhooks/whk_xxxxxxxx \
-H "Authorization: Bearer un_your_api_key"
```
## Best Practices
* ✓ **Always verify signatures** to ensure webhooks are from Unosend
* ✓ **Return 200 quickly** and process events asynchronously
* ✓ **Handle duplicates** - use event ID for idempotency
* ✓ **Log all events** for debugging and auditing
* ✓ **Use HTTPS** for your webhook endpoint
# Introduction
Source: https://docs.unosend.co/introduction
Unosend is a transactional email service for developers. Send emails with REST API or SMTP.
Unosend is a dedicated transactional email service designed to deliver time-sensitive emails triggered by user actions — such as OTPs, order confirmations, password resets, invoices, and more. It ensures faster delivery, higher inbox placement, and reliable security.
Unosend is for sending transactional emails only. Marketing or bulk promotional emails are not supported to maintain maximum deliverability and sender reputation.
## Features
* **REST API & SMTP** — Send via `api.unosend.co` or `smtp.unosend.co:587`
* **Email templates** — Create, manage, and send with dynamic merge tags
* **Domain authentication** — SPF, DKIM, and DMARC verification
* **Real-time webhooks** — Get notified on delivery, bounce, open, and click events
* **Suppression management** — Automatic bounce/complaint handling + manual suppression lists
* **Email logs & exports** — Full delivery logs with export capability
* **File cache** — Upload and reuse attachments/inline images across emails
* **Dedicated IP** — Available for high-volume senders
* **Open & click tracking** — Built-in tracking with per-email control
* **Batch sending** — Send to multiple recipients in a single API call
```bash theme={null}
curl -X POST https://api.unosend.co/v1/email \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"from": {"address": "hello@yourdomain.com", "name": "Your App"},
"to": [{"email_address": {"address": "user@example.com", "name": "User"}}],
"subject": "Hello from Unosend",
"htmlbody": "Your first email.
"
}'
```
## Get Started
Send your first email in 5 minutes
API keys and security
Verify your sending domain
Full endpoint documentation
# Quick Start
Source: https://docs.unosend.co/quickstart
Send your first email in under 5 minutes.
## 1. Get Onboarded
[Book a call](https://cal.com/unosend/onboarding) or [contact us](https://unosend.co/contact) to get set up. We'll provision your account and provide your Send Mail Token.
## 2. Add a Domain
Add your sending domain and configure the DNS records we provide (SPF, DKIM, CNAME tracking).
```bash theme={null}
# Add domain
curl -X POST https://api.unosend.co/v1/domains \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{"domain": "yourdomain.com"}'
# Verify after adding DNS records
curl -X POST https://api.unosend.co/v1/domains/{id}/verify \
-H "Authorization: Bearer un_your_api_key"
```
## 3. Send an Email
```bash cURL theme={null}
curl -X POST https://api.unosend.co/v1/emails \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"from": "hello@yourdomain.com",
"to": ["user@example.com"],
"subject": "Hello from Unosend",
"html": "Welcome!
Your first email.
"
}'
```
```javascript Node.js theme={null}
const res = await fetch('https://api.unosend.co/v1/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.UNOSEND_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: 'hello@yourdomain.com',
to: ['user@example.com'],
subject: 'Hello from Unosend',
html: 'Welcome!
Your first email.
'
})
});
console.log(await res.json());
```
```python Python theme={null}
import requests
res = requests.post(
'https://api.unosend.co/v1/emails',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
json={
'from': 'hello@yourdomain.com',
'to': ['user@example.com'],
'subject': 'Hello from Unosend',
'html': 'Welcome!
Your first email.
'
}
)
print(res.json())
```
**Response:**
```json theme={null}
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"from": "hello@yourdomain.com",
"to": ["user@example.com"],
"status": "queued"
}
```
## Next Steps
Set up SPF and DKIM
See all endpoints
# Error Codes
Source: https://docs.unosend.co/resources/error-codes
Complete reference of error codes returned by the Unosend API and how to handle them.
## Error Response Format
When an error occurs, the API returns a JSON response with the following structure:
```json error-response.json theme={null}
{
"error": {
"code": "invalid_api_key",
"message": "The API key provided is invalid or has been revoked.",
"status": 401,
"details": {
"api_key_prefix": "un_xxx..."
}
}
}
```
| Field | Type | Description |
| --------- | ------ | --------------------------------- |
| `code` | string | Machine-readable error identifier |
| `message` | string | Human-readable error description |
| `status` | number | HTTP status code |
| `details` | object | Additional context (optional) |
## HTTP Status Codes
Request was successful
Something was wrong with the request
Something went wrong on our end
## Authentication Errors
| Code | Status | Description |
| -------------------------- | ------ | ---------------------------------- |
| `missing_api_key` | 401 | No API key provided in request |
| `invalid_api_key` | 401 | API key is invalid or revoked |
| `api_key_expired` | 401 | API key has expired |
| `insufficient_permissions` | 403 | API key lacks required permissions |
### How to Fix
```bash Terminal theme={null}
# Correct format: Include API key in Authorization header
curl -X POST "https://api.unosend.co/emails" \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{"from": "hello@yourdomain.com", "to": "user@example.com", "subject": "Test", "html": "Hello
"}'
```
**Common mistake:** Make sure you're using `Bearer` prefix before your API key.
The format should be `Authorization: Bearer un_your_api_key`.
## Validation Errors
| Code | Status | Description |
| ---------------------------- | ------ | ------------------------------------- |
| `validation_error` | 400 | Request body failed validation |
| `missing_required_field` | 400 | Required field is missing |
| `invalid_email_address` | 400 | Email address format is invalid |
| `invalid_from_address` | 400 | From address domain not verified |
| `invalid_template_variables` | 400 | Template variables don't match schema |
| `attachment_too_large` | 400 | Attachment exceeds size limit (10MB) |
| `invalid_json` | 400 | Request body is not valid JSON |
### Example Validation Error
```json validation-error.json theme={null}
{
"error": {
"code": "validation_error",
"message": "Request validation failed",
"status": 400,
"details": {
"errors": [
{
"field": "to",
"message": "must be a valid email address",
"value": "not-an-email"
},
{
"field": "subject",
"message": "is required",
"value": null
}
]
}
}
}
```
### Handling Validation Errors
```typescript handle-validation.ts theme={null}
const response = await fetch('https://api.unosend.co/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (response.status === 400) {
const error = await response.json();
if (error.error.code === 'validation_error') {
// Log each field error
error.error.details.errors.forEach((e: any) => {
console.error(`Field '${e.field}': ${e.message}`);
});
}
}
```
## Resource Errors
| Code | Status | Description |
| -------------------- | ------ | ---------------------- |
| `not_found` | 404 | Resource doesn't exist |
| `email_not_found` | 404 | Email ID not found |
| `domain_not_found` | 404 | Domain not found |
| `template_not_found` | 404 | Template ID not found |
| `webhook_not_found` | 404 | Webhook not found |
### Example 404 Response
```json not-found.json theme={null}
{
"error": {
"code": "email_not_found",
"message": "Email with ID 'em_abc123' not found",
"status": 404,
"details": {
"email_id": "em_abc123"
}
}
}
```
## Rate Limit Errors
| Code | Status | Description |
| ---------------------- | ------ | ---------------------------- |
| `rate_limit_exceeded` | 429 | Too many requests per second |
| `daily_limit_exceeded` | 429 | Daily email limit reached |
| `quota_exceeded` | 429 | Monthly quota exceeded |
### Rate Limit Response
```json rate-limit.json theme={null}
{
"error": {
"code": "rate_limit_exceeded",
"message": "Rate limit exceeded. Retry after 60 seconds.",
"status": 429,
"details": {
"retry_after": 60,
"limit": 100,
"remaining": 0,
"reset_at": "2024-01-15T10:30:00Z"
}
}
}
```
See the [Rate Limits](/resources/rate-limits) documentation for handling strategies and retry logic examples.
## Domain Errors
| Code | Status | Description |
| ---------------------------- | ------ | ---------------------------------------------- |
| `domain_not_verified` | 400 | Domain has not been verified yet |
| `domain_verification_failed` | 400 | DNS records not found or incorrect |
| `domain_already_exists` | 409 | Domain already registered in another workspace |
| `dkim_verification_failed` | 400 | DKIM record not found or invalid |
| `spf_verification_failed` | 400 | SPF record not found or invalid |
See [Domain Verification](/guides/domain-verification) guide for setting up DNS records correctly.
## Server Errors
| Code | Status | Description |
| ----------------------- | ------ | -------------------------------------- |
| `internal_server_error` | 500 | Unexpected server error |
| `service_unavailable` | 503 | Service temporarily unavailable |
| `gateway_timeout` | 504 | Request timed out |
| `email_delivery_failed` | 500 | Failed to deliver email to mail server |
**5xx errors** are rare and usually temporary. Implement retry logic with exponential backoff for these errors.
## Complete Error Handling Example
```typescript JavaScript/TypeScript theme={null}
interface UnosendError {
error: {
code: string;
message: string;
status: number;
details?: Record;
};
}
async function sendEmail(payload: EmailPayload): Promise {
const response = await fetch('https://api.unosend.co/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const error: UnosendError = await response.json();
switch (error.error.code) {
case 'invalid_api_key':
case 'missing_api_key':
throw new Error('Authentication failed. Check your API key.');
case 'validation_error':
const fields = error.error.details?.errors
?.map((e: any) => `${e.field}: ${e.message}`)
.join(', ');
throw new Error(`Validation failed: ${fields}`);
case 'rate_limit_exceeded':
const retryAfter = error.error.details?.retry_after || 60;
// Implement retry logic
await sleep(retryAfter * 1000);
return sendEmail(payload); // Retry once
case 'domain_not_verified':
throw new Error('Verify your domain before sending emails.');
case 'quota_exceeded':
throw new Error('Monthly email quota exceeded. Upgrade your plan.');
case 'internal_server_error':
case 'service_unavailable':
// Retry with exponential backoff
throw new Error('Service temporarily unavailable. Please retry.');
default:
throw new Error(error.error.message);
}
}
return response.json();
}
```
```python Python theme={null}
import requests
import time
class UnosendError(Exception):
def __init__(self, code, message, status, details=None):
self.code = code
self.message = message
self.status = status
self.details = details or {}
super().__init__(message)
def send_email(payload):
api_key = "un_your_api_key"
response = requests.post(
"https://api.unosend.co/emails",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
},
json=payload
)
if not response.ok:
error = response.json()["error"]
if error["code"] == "rate_limit_exceeded":
retry_after = error.get("details", {}).get("retry_after", 60)
time.sleep(retry_after)
return send_email(payload) # Retry
if error["code"] == "validation_error":
errors = error.get("details", {}).get("errors", [])
fields = ", ".join([f"{e['field']}: {e['message']}" for e in errors])
raise UnosendError(
error["code"],
f"Validation failed: {fields}",
error["status"],
error.get("details")
)
raise UnosendError(
error["code"],
error["message"],
error["status"],
error.get("details")
)
return response.json()
```
```bash cURL Error Checking theme={null}
# Check HTTP status code and response
response=$(curl -s -w "\n%{http_code}" -X POST "https://api.unosend.co/emails" \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
-d '{"from": "hello@yourdomain.com", "to": "user@example.com", "subject": "Test", "html": "Hello
"}')
status=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [ "$status" -ge 400 ]; then
echo "Error ($status): $body"
else
echo "Success: $body"
fi
```
## Quick Reference
* `429` Rate limit exceeded
* `500` Internal server error
* `503` Service unavailable
* `504` Gateway timeout
* `400` Validation error
* `401` Authentication error
* `403` Permission denied
* `404` Resource not found
# Rate Limits
Source: https://docs.unosend.co/resources/rate-limits
Understand API rate limits per plan and how to handle them in your applications.
## Overview
Rate limits protect the API from abuse and ensure fair usage for all users. Limits are applied **per organization** using an in-memory sliding window.
### API Request Limits
| Tier | Requests/Second | Requests/Minute | Requests/Day |
| --------------- | --------------- | --------------- | ------------ |
| **Standard** | 10 | 500 | 50,000 |
| **High Volume** | 50 | 2,000 | 200,000 |
Need higher limits? [Contact us](/contact) to discuss your volume requirements.
### Email Sending
Unosend uses a credit-based system. 1 credit = 1 email. [Contact us](https://unosend.co/contact) for pricing and volume details.
* No subscription — buy credits when you need them
* Email size limit: **15 MB** (headers + body + inline images + attachments)
### Domain Sending Limit
There is a global daily limit of **200,000 emails per sender domain** across all plans. This protects shared infrastructure and ensures deliverability.
### Domain Creation Rate Limit
All plans include **unlimited domains**. To prevent abuse, domain creation is rate limited to **10 domains per hour** per organization. This is a velocity cap — there is no limit on the total number of domains you can add.
| Limit | Value |
| ---------------- | --------------------- |
| Domains per hour | 10 |
| Total domains | Unlimited (all plans) |
If you exceed this limit, the API returns `429 Too Many Requests`. Wait and retry after a few minutes.
## Rate Limit Headers
Every API response includes headers to help you track your rate limit status:
| Header | Description |
| ----------------------- | -------------------------------------- |
| `X-RateLimit-Limit` | Maximum requests allowed per window |
| `X-RateLimit-Remaining` | Requests remaining in current window |
| `X-RateLimit-Reset` | Unix timestamp when window resets |
| `Retry-After` | Seconds to wait (only on 429 response) |
### Example Response Headers
```txt response-headers.txt theme={null}
HTTP/1.1 200 OK
X-RateLimit-Limit: 500
X-RateLimit-Remaining: 485
X-RateLimit-Reset: 1705320060
Content-Type: application/json
```
## Check Current Usage
You can check your current rate limit status with any API request by inspecting the response headers, or use the usage endpoint:
```bash Terminal theme={null}
curl -X GET "https://api.unosend.co/usage" \
-H "Authorization: Bearer un_your_api_key" \
-i
```
### Response
```json response.json theme={null}
{
"credits_remaining": 37550,
"credits_used": 12450,
"credits_total": 50000,
"credits_expire_at": "2026-07-01T00:00:00Z"
}
```
## Handling Rate Limits
When you exceed the rate limit, the API returns a `429 Too Many Requests` response:
```json rate-limit-response.json theme={null}
{
"error": {
"code": "rate_limit_exceeded",
"message": "Rate limit exceeded. Retry after 60 seconds.",
"retry_after": 60
}
}
```
### Implementing Retry Logic
```bash cURL with Retry theme={null}
# Use --retry flag for automatic retries
curl -X POST "https://api.unosend.co/emails" \
-H "Authorization: Bearer un_your_api_key" \
-H "Content-Type: application/json" \
--retry 3 \
--retry-delay 5 \
-d '{"from": "hello@yourdomain.com", "to": "user@example.com", "subject": "Hello", "html": "Hi!
"}'
```
```typescript JavaScript/TypeScript theme={null}
async function sendEmailWithRetry(
payload: EmailPayload,
maxRetries: number = 3
): Promise {
for (let attempt = 0; attempt < maxRetries; attempt++) {
const response = await fetch('https://api.unosend.co/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (response.status === 429) {
const retryAfter = parseInt(
response.headers.get('Retry-After') || '60'
);
console.log(`Rate limited. Waiting ${retryAfter} seconds...`);
await sleep(retryAfter * 1000);
continue;
}
return response;
}
throw new Error('Max retries exceeded');
}
function sleep(ms: number): Promise {
return new Promise(resolve => setTimeout(resolve, ms));
}
```
```python Python theme={null}
import requests
import time
def send_email_with_retry(payload, max_retries=3):
api_key = "un_your_api_key"
for attempt in range(max_retries):
response = requests.post(
"https://api.unosend.co/emails",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
},
json=payload
)
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", 60))
print(f"Rate limited. Waiting {retry_after} seconds...")
time.sleep(retry_after)
continue
return response
raise Exception("Max retries exceeded")
```
## Exponential Backoff
For robust retry logic, use exponential backoff with jitter to avoid thundering herd:
```typescript exponential-backoff.ts theme={null}
async function sendWithExponentialBackoff(
payload: EmailPayload,
maxRetries: number = 5
): Promise {
const baseDelay = 1000; // 1 second
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch('https://api.unosend.co/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (response.status === 429) {
// Calculate delay with exponential backoff + jitter
const delay = baseDelay * Math.pow(2, attempt);
const jitter = Math.random() * 1000;
const waitTime = delay + jitter;
console.log(`Rate limited. Waiting ${waitTime}ms (attempt ${attempt + 1})`);
await sleep(waitTime);
continue;
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response;
} catch (error) {
if (attempt === maxRetries - 1) throw error;
const delay = baseDelay * Math.pow(2, attempt);
await sleep(delay);
}
}
throw new Error('Max retries exceeded');
}
```
## Queue Pattern for Bulk Sending
For sending many emails, use a queue with rate limiting to stay within limits:
```typescript rate-limited-queue.ts theme={null}
class RateLimitedQueue {
private queue: EmailPayload[] = [];
private processing = false;
private requestsPerSecond: number;
constructor(requestsPerSecond: number = 10) {
this.requestsPerSecond = requestsPerSecond;
}
async add(payload: EmailPayload): Promise {
this.queue.push(payload);
this.process();
}
private async process(): Promise {
if (this.processing) return;
this.processing = true;
const interval = 1000 / this.requestsPerSecond;
while (this.queue.length > 0) {
const payload = this.queue.shift()!;
try {
await sendEmailWithRetry(payload);
} catch (error) {
console.error('Failed to send email:', error);
}
await sleep(interval);
}
this.processing = false;
}
}
// Usage
const queue = new RateLimitedQueue(10); // 10 req/sec
for (const recipient of recipients) {
queue.add({
from: 'hello@yourdomain.com',
to: recipient.email,
subject: 'Hello!',
html: 'Your email content
'
});
}
```
For bulk sending, consider using the `/emails/batch` endpoint which allows up to 100 emails per request, significantly reducing API calls.
## Best Practices
Check `X-RateLimit-Remaining` and slow down before hitting limits.
Send multiple emails in one request using `POST /emails/batch` to reduce API calls.
Queue emails during high-traffic periods and process them at a controlled rate.
Instead of polling for status, use webhooks to receive delivery updates asynchronously.
Cache responses from endpoints like `GET /domains` to reduce unnecessary requests.
## Need Higher Limits?
If you need higher rate limits for your use case, upgrade your plan or contact us for Enterprise options with custom limits.
* [View Plans →](https://www.unosend.co/pricing)
* [Contact Sales →](mailto:support@unosend.co)