TutorialsSend Your First Email

Send Your First Email

Learn how to send your first email using the FormaMail API in just a few minutes.


Overview

This tutorial walks you through sending a template-based email using the FormaMail API. By the end, you’ll understand how to:

  • Create an API key for authentication
  • Find your template ID
  • Send an email with dynamic variables
  • Check the delivery status

Prerequisites

Before starting, make sure you have:

  • An active FormaMail account (Sign up here)
  • At least one email template created (or use the default welcome template)
  • Basic knowledge of making HTTP requests (cURL, JavaScript, or Python)
  • Node.js installed (optional, for JavaScript examples)

Tutorial: Send Your First Template Email

Step 1: Create an API Key

First, you need an API key to authenticate with the FormaMail API.

  1. Log in to your FormaMail Dashboard
  2. Navigate to Settings → API Keys
  3. Click Create New API Key
  4. Enter a name (e.g., “My First Integration”)
  5. Select permissions:
    • âś… Send Emails
    • âś… View Templates (optional)
  6. Click Create Key
⚠️

Important: Copy your API key immediately and store it securely. You won’t be able to see it again!

Your API key will look like this:

fm_sk_abc123xyz456def789...

Store it in an environment variable:

export FORMAMAIL_API_KEY="fm_sk_abc123xyz456def789..."

Step 2: Get a Template

Every email in FormaMail uses a template. You have three options to get started quickly:

The fastest way to create a template:

  1. Go to Templates → Create Template
  2. Click Generate with AI
  3. Describe what you need, for example:

    “Welcome email for new users with a greeting, brief introduction to our service, and a button to get started”

  4. AI generates a complete template with variables
  5. Review, customize if needed, and click Publish
  6. Copy the Template ID

AI understands context: Describe your use case naturally. Include details like “include a tracking button” or “show order items in a table” for more tailored results.

Use professionally designed templates:

  1. Go to Templates → Template Gallery
  2. Browse categories: Transactional, Marketing, Notifications
  3. Find a template that matches your needs (e.g., “Welcome Email”, “Order Confirmation”)
  4. Click Import to add it to your templates
  5. Customize the content and branding
  6. Click Publish
  7. Copy the Template ID

Option C: Create Manually

Build from scratch with full control:

  1. Go to Templates → Create Template → Email Template
  2. Use the drag-and-drop designer to build your layout
  3. Add components and variables
  4. Click Publish

See the Create an Email Template tutorial for detailed manual creation steps.


Finding Your Template ID:

Once you have a template, find its ID:

  1. Go to Templates in your dashboard
  2. Click on the template
  3. Copy the Template ID from the URL or settings panel

Template IDs come in different formats:

  • UUID: 550e8400-e29b-41d4-a716-446655440000
  • Short ID: etpl_a1b2c3d4
  • Slug: welcome-email (unique per team)

Step 3: Understand the Template Variables

Open your template to see what variables it expects. For example, a welcome email template might use:

  • {{firstName}} - The recipient’s first name
  • {{companyName}} - Your company name
  • {{loginUrl}} - Link to sign in

You’ll pass these values when sending the email.

Step 4: Send the Email

Now let’s send the email! Choose your preferred method:

Using cURL

curl -X POST https://api.formamail.com/api/emails/send \
  -H "Authorization: Bearer $FORMAMAIL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "templateId": "your-template-id",
    "to": [
      {
        "email": "recipient@example.com",
        "name": "John Doe"
      }
    ],
    "variables": {
      "firstName": "John",
      "companyName": "Acme Corp",
      "loginUrl": "https://app.example.com/login"
    }
  }'

Using JavaScript/Node.js

Create a file called send-email.js:

const axios = require('axios');
 
const API_KEY = process.env.FORMAMAIL_API_KEY;
const API_URL = 'https://api.formamail.com/api';
 
async function sendFirstEmail() {
  try {
    const response = await axios.post(
      `${API_URL}/emails/send`,
      {
        templateId: 'your-template-id',
        to: [
          {
            email: 'recipient@example.com',
            name: 'John Doe'
          }
        ],
        variables: {
          firstName: 'John',
          companyName: 'Acme Corp',
          loginUrl: 'https://app.example.com/login'
        }
      },
      {
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json'
        }
      }
    );
 
    console.log('Email sent successfully!');
    console.log('Email ID:', response.data.id);
    console.log('Status:', response.data.status);
    return response.data;
  } catch (error) {
    console.error('Error sending email:');
    console.error(error.response?.data || error.message);
    throw error;
  }
}
 
sendFirstEmail();

Run the script:

npm install axios
node send-email.js

Using Python

Create a file called send_email.py:

import requests
import os
 
API_KEY = os.getenv('FORMAMAIL_API_KEY')
API_URL = 'https://api.formamail.com/api'
 
def send_first_email():
    response = requests.post(
        f'{API_URL}/emails/send',
        headers={
            'Authorization': f'Bearer {API_KEY}',
            'Content-Type': 'application/json'
        },
        json={
            'templateId': 'your-template-id',
            'to': [
                {
                    'email': 'recipient@example.com',
                    'name': 'John Doe'
                }
            ],
            'variables': {
                'firstName': 'John',
                'companyName': 'Acme Corp',
                'loginUrl': 'https://app.example.com/login'
            }
        }
    )
 
    if response.ok:
        data = response.json()
        print('Email sent successfully!')
        print(f"Email ID: {data['id']}")
        print(f"Status: {data['status']}")
        return data
    else:
        print(f'Error: {response.status_code}')
        print(response.json())
        raise Exception('Failed to send email')
 
if __name__ == '__main__':
    send_first_email()

Run the script:

pip install requests
python send_email.py

Step 5: Check the Response

A successful response looks like this:

{
  "id": "770e8400-e29b-41d4-a716-446655440000",
  "messageId": "<1234567890@formamail.com>",
  "status": "queued",
  "recipientCount": 1,
  "attachmentCount": 0,
  "queuedAt": "2024-11-19T12:00:00.000Z",
  "estimatedDeliveryAt": "2024-11-19T12:00:30.000Z"
}

Response fields explained:

  • id - Unique identifier for tracking this email
  • status - Current status (queued → processing → sent → delivered)
  • queuedAt - When the email entered the queue
  • estimatedDeliveryAt - When you can expect delivery

Step 6: Verify Delivery

Check the email status in your dashboard:

  1. Go to Email Logs in your dashboard
  2. Find your email by ID or recipient
  3. View the delivery status and any events

Or use the API:

curl https://api.formamail.com/api/emails/770e8400-e29b-41d4-a716-446655440000 \
  -H "Authorization: Bearer $FORMAMAIL_API_KEY"

Adding Optional Features

CC and BCC Recipients

Send copies to additional recipients:

{
  templateId: 'your-template-id',
  to: [{ email: 'primary@example.com', name: 'Primary Contact' }],
  cc: [{ email: 'manager@example.com', name: 'Manager' }],
  bcc: [{ email: 'archive@example.com' }],
  variables: { /* ... */ }
}

Reply-To Address

Set a custom reply-to address:

{
  templateId: 'your-template-id',
  to: [{ email: 'customer@example.com' }],
  replyTo: 'support@yourcompany.com',
  variables: { /* ... */ }
}

Email Priority

Set email priority for important messages:

{
  templateId: 'your-template-id',
  to: [{ email: 'customer@example.com' }],
  priority: 'high', // 'low', 'normal', or 'high'
  variables: { /* ... */ }
}

Schedule for Later

Send an email at a specific time:

{
  templateId: 'your-template-id',
  to: [{ email: 'customer@example.com' }],
  scheduledAt: '2024-12-25T09:00:00Z', // ISO 8601 format
  variables: { /* ... */ }
}

Add Tags for Tracking

Categorize emails with tags:

{
  templateId: 'your-template-id',
  to: [{ email: 'customer@example.com' }],
  tags: ['welcome', 'onboarding', 'automated'],
  variables: { /* ... */ }
}

Complete Example

Here’s a complete example with all common options:

const axios = require('axios');
 
async function sendWelcomeEmail(user) {
  const response = await axios.post(
    'https://api.formamail.com/api/emails/send',
    {
      templateId: 'welcome-email',
      to: [
        {
          email: user.email,
          name: `${user.firstName} ${user.lastName}`
        }
      ],
      cc: user.manager ? [{ email: user.manager.email }] : [],
      replyTo: 'onboarding@yourcompany.com',
      variables: {
        firstName: user.firstName,
        lastName: user.lastName,
        companyName: 'Acme Corp',
        loginUrl: `https://app.example.com/login?token=${user.token}`,
        supportEmail: 'support@yourcompany.com'
      },
      tags: ['welcome', 'onboarding'],
      metadata: {
        userId: user.id,
        source: 'signup-flow'
      }
    },
    {
      headers: {
        'Authorization': `Bearer ${process.env.FORMAMAIL_API_KEY}`,
        'Content-Type': 'application/json'
      }
    }
  );
 
  console.log(`Welcome email sent to ${user.email}`);
  return response.data;
}
 
// Example usage
sendWelcomeEmail({
  id: 'user-123',
  firstName: 'John',
  lastName: 'Doe',
  email: 'john.doe@example.com',
  token: 'abc123'
});

Troubleshooting

401 Unauthorized

Issue: API returns 401 error.

Solutions:

  1. âś… Verify your API key is correct
  2. ✅ Check the key hasn’t been revoked in Settings
  3. âś… Ensure the Authorization header format is Bearer YOUR_KEY
  4. ✅ Confirm the key has “Send Emails” permission

404 Template Not Found

Issue: API returns template not found error.

Solutions:

  1. âś… Double-check the template ID
  2. âś… Ensure the template is published (not just saved as draft)
  3. âś… Verify the template belongs to your team
  4. âś… Try using the UUID format instead of slug

Missing Variables

Issue: Email sends but variables show as {{variableName}}.

Solutions:

  1. âś… Check variable names match exactly (case-sensitive)
  2. âś… Ensure all required variables are provided
  3. âś… Verify variable values are not null or undefined

Email Not Received

Issue: API shows success but email not in inbox.

Solutions:

  1. âś… Check spam/junk folder
  2. âś… Verify recipient email is correct
  3. âś… Check Email Logs for delivery status
  4. âś… Ensure recipient is not on suppression list

Next Steps

Congratulations! You’ve sent your first email with FormaMail. Here’s what to explore next: