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.
- Log in to your FormaMail Dashboard
- Navigate to Settings → API Keys
- Click Create New API Key
- Enter a name (e.g., “My First Integration”)
- Select permissions:
- âś… Send Emails
- âś… View Templates (optional)
- 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:
Option A: Generate with AI (Recommended for beginners)
The fastest way to create a template:
- Go to Templates → Create Template
- Click Generate with AI
- 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”
- AI generates a complete template with variables
- Review, customize if needed, and click Publish
- 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.
Option B: Import from Template Gallery
Use professionally designed templates:
- Go to Templates → Template Gallery
- Browse categories: Transactional, Marketing, Notifications
- Find a template that matches your needs (e.g., “Welcome Email”, “Order Confirmation”)
- Click Import to add it to your templates
- Customize the content and branding
- Click Publish
- Copy the Template ID
Option C: Create Manually
Build from scratch with full control:
- Go to Templates → Create Template → Email Template
- Use the drag-and-drop designer to build your layout
- Add components and variables
- 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:
- Go to Templates in your dashboard
- Click on the template
- 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.jsUsing 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.pyStep 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 emailstatus- Current status (queued→processing→sent→delivered)queuedAt- When the email entered the queueestimatedDeliveryAt- When you can expect delivery
Step 6: Verify Delivery
Check the email status in your dashboard:
- Go to Email Logs in your dashboard
- Find your email by ID or recipient
- 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:
- âś… Verify your API key is correct
- ✅ Check the key hasn’t been revoked in Settings
- âś… Ensure the Authorization header format is
Bearer YOUR_KEY - ✅ Confirm the key has “Send Emails” permission
404 Template Not Found
Issue: API returns template not found error.
Solutions:
- âś… Double-check the template ID
- âś… Ensure the template is published (not just saved as draft)
- âś… Verify the template belongs to your team
- âś… Try using the UUID format instead of slug
Missing Variables
Issue: Email sends but variables show as {{variableName}}.
Solutions:
- âś… Check variable names match exactly (case-sensitive)
- âś… Ensure all required variables are provided
- âś… Verify variable values are not null or undefined
Email Not Received
Issue: API shows success but email not in inbox.
Solutions:
- âś… Check spam/junk folder
- âś… Verify recipient email is correct
- âś… Check Email Logs for delivery status
- âś… Ensure recipient is not on suppression list
Next Steps
Congratulations! You’ve sent your first email with FormaMail. Here’s what to explore next:
- Create an Email Template - Design beautiful templates with the visual editor
- Generate PDF Invoices - Attach dynamically generated PDFs
- Send Bulk Personalized Emails - Send to hundreds of recipients at once
- API Reference - Full API documentation