Developer GuideAuthentication

Authentication

Learn how to authenticate with the FormaMail API using API keys for sending emails programmatically.

Overview

FormaMail uses API keys for authentication when sending emails programmatically. API keys allow you to send emails without exposing your account credentials.

Important: API keys are specifically designed for programmatic API access (server-to-server). Email/password authentication with JWT tokens is only used by the web dashboard and admin applications - it should NOT be used for external API access.


API Keys

What are API Keys?

API keys are secure tokens that authenticate your application when making requests to the FormaMail API. They act as a password for programmatic access.

Key Features:

  • Scoped Permissions: Limit what each key can do
  • Revocable: Disable a key without changing your password
  • Trackable: Monitor usage per key
  • Expirable: Set expiration dates for enhanced security

Creating an API Key

  1. Navigate to Settings → API Keys in the dashboard
  2. Click Create API Key
  3. Configure the key:
    • Name: Descriptive name (e.g., “Production Server”, “Dev Environment”)
    • Permissions: Select what this key can do (send emails, read analytics, etc.)
    • Expiration: Optional expiry date (recommended for security)
  4. Click Create Key
  5. IMPORTANT: Copy the key immediately - it won’t be shown again

API Key Format: fm_sk_abc123xyz456def789...


Using API Keys

Authorization Header

Include your API key in the Authorization header with the Bearer scheme:

curl https://api.formamail.com/api/emails/send \
  -H "Authorization: Bearer fm_sk_abc123xyz456..." \
  -H "Content-Type: application/json" \
  -X POST \
  -d '{
    "templateId": "tmpl_welcome",
    "to": [{ "email": "user@example.com", "name": "John Doe" }],
    "variables": { "firstName": "John", "companyName": "Acme Corp" }
  }'

Note: All emails must use a template. Templates are created in the Dashboard. The templateId field is required.

JavaScript Example

const apiKey = 'fm_sk_abc123xyz456...';
 
const response = await fetch('https://api.formamail.com/api/emails/send', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    templateId: 'tmpl_welcome',
    to: [{ email: 'user@example.com', name: 'John Doe' }],
    variables: {
      firstName: 'John',
      companyName: 'Acme Corp'
    }
  })
});
 
const data = await response.json();
console.log('Email sent:', data.id);

Python Example

import requests
 
api_key = 'fm_sk_abc123xyz456...'
url = 'https://api.formamail.com/api/emails/send'
 
headers = {
    'Authorization': f'Bearer {api_key}',
    'Content-Type': 'application/json'
}
 
payload = {
    'templateId': 'tmpl_welcome',
    'to': [{
        'email': 'user@example.com',
        'name': 'John Doe'
    }],
    'variables': {
        'firstName': 'John',
        'companyName': 'Acme Corp'
    }
}
 
response = requests.post(url, json=payload, headers=headers)
data = response.json()
print('Email sent:', data['id'])

What Can API Keys Access?

API keys provide access to email sending and related operations:

Available Endpoints

EndpointDescriptionDocumentation
POST /api/emails/sendSend single emailSending Emails
POST /api/emails/send/bulkSend bulk personalized emailsSending Emails
⚠️

Permissions: API keys have limited permissions for security. They can send emails using existing templates but cannot:

  • Create or modify templates (dashboard only)
  • Access analytics (dashboard only)
  • Manage team members (dashboard only)
  • Change billing settings (dashboard only)

This ensures that even if an API key is compromised, attackers cannot modify your templates or access sensitive data.


API Key Format

API keys use the format fm_sk_{random_string}:

  • Prefix: fm_sk_
  • Random String: Cryptographically secure identifier
  • Best Practice: Store securely, rotate regularly

Security Best Practices

1. Keep Keys Secret

âś… DO:

  • Store keys in environment variables
  • Use secret management services (AWS Secrets Manager, HashiCorp Vault)
  • Rotate keys regularly (every 90 days)

❌ DON’T:

  • Commit keys to version control
  • Hardcode keys in client-side code
  • Share keys via email or chat

2. Use Environment Variables

# .env file (add to .gitignore)
FORMAMAIL_API_KEY=fm_sk_abc123xyz456...
// JavaScript
const apiKey = process.env.FORMAMAIL_API_KEY;
# Python
import os
api_key = os.environ.get('FORMAMAIL_API_KEY')

3. Limit Permissions

Grant the minimum permissions needed:

{
  "name": "Email Sender Service",
  "permissions": ["emails:send"],  // Only what's needed
  "expiresAt": "2025-12-31T23:59:59Z"
}

4. Set Expiration Dates

Always set an expiration date for long-lived keys:

{
  "name": "Q4 Campaign Key",
  "permissions": ["emails:send"],
  "expiresAt": "2025-12-31T23:59:59Z"  // Auto-revokes after date
}

5. Monitor Usage

Regularly review API key usage in the dashboard:

  • Check for unexpected activity
  • Monitor request volume
  • Review permission usage

6. Rotate Keys

Implement key rotation:

  1. Create a new API key
  2. Update your application with the new key
  3. Test thoroughly
  4. Delete the old key

Error Handling

Invalid API Key

Status Code: 401 Unauthorized

{
  "statusCode": 401,
  "code": "ERR_AUTH_001",
  "message": "Invalid API key",
  "timestamp": "2025-11-07T10:30:00.000Z",
  "path": "/api/emails/send"
}

Expired API Key

Status Code: 401 Unauthorized

{
  "statusCode": 401,
  "code": "ERR_AUTH_002",
  "message": "API key has expired",
  "timestamp": "2025-11-07T10:30:00.000Z",
  "path": "/api/emails/send",
  "relatedInfo": {
    "expiresAt": "2025-10-31T23:59:59Z"
  }
}

Insufficient Permissions

Status Code: 403 Forbidden

{
  "statusCode": 403,
  "code": "ERR_AUTH_003",
  "message": "Insufficient permissions",
  "timestamp": "2025-11-07T10:30:00.000Z",
  "path": "/api/templates/create",
  "relatedInfo": {
    "required": "templates:create",
    "granted": ["emails:send"]
  }
}

Rate Limiting

API keys are subject to rate limits based on your plan:

PlanRequests per Minute
Free10
Starter100
Pro1000
EnterpriseCustom

See Rate Limiting for details.


Managing API Keys

All API key management operations are performed through the dashboard at Settings → API Keys.

Available operations:

  • View all keys: See all active and expired keys
  • Create new key: Generate a new API key
  • View key details: Check creation date, last used, and expiration
  • Revoke key: Immediately disable a key
  • Set expiration: Add or update expiration date

Dashboard-Only: For security reasons, API key management is not available via API keys themselves. Use the dashboard to create, view, and revoke keys.


Common Questions

How many API keys can I create?

There’s no limit on the number of API keys you can create. We recommend creating separate keys for each environment and service.

What happens if my key is compromised?

Immediately revoke the compromised key in the dashboard or via API. Create a new key with different permissions and update your applications.

Can I use the same key in multiple environments?

While possible, it’s not recommended. Use separate keys for development, staging, and production environments.

Do API keys expire automatically?

Only if you set an expiration date. Keys without an expiration date remain active until manually revoked.

Can I recover a deleted API key?

No, deleted keys cannot be recovered. You’ll need to create a new key.


Related: Sending Emails | Error Handling | Rate Limiting