Email SDK
Send emails to contacts, tags, segments, or direct email addresses using templates or raw HTML content.
Quick Start
The simplest way to send an email:
import Sendmator from '@sendmator/node';
const sendmator = new Sendmator({ apiKey: 'sk_test_...' });
// Send with template
await sendmator.email.sendTo('user@example.com', {
template_key: 'welcome-email',
variables: { name: 'John' }
});
Simple Methods (Recommended)
Send to Email Address
The easiest way to send an email - no contact database required:
// Using a template
await sendmator.email.sendTo('user@example.com', {
template_key: 'welcome-email',
variables: { name: 'John', company: 'Acme Corp' }
});
// With custom HTML content
await sendmator.email.sendTo('user@example.com', {
subject: 'Welcome!',
html: '<h1>Hello John!</h1><p>Thanks for signing up.</p>',
text: 'Hello John! Thanks for signing up.'
});
// With additional details
await sendmator.email.sendTo('user@example.com', {
template_key: 'verify-api-otp',
first_name: 'John',
last_name: 'Doe',
variables: {
company: 'Acme Corp',
OTP_CODE: 123456
},
from_email: 'hello@acme.com',
from_name: 'Acme Team'
});
Send to Existing Contact
Send to a contact in your Sendmator database:
await sendmator.email.sendToContact('user-123', {
template_key: 'order-confirmation',
variables: {
order_id: 'ORD-456',
total: '$99.99'
}
});
// With custom sender
await sendmator.email.sendToContact('user-123', {
template_key: 'welcome',
variables: { company: 'Acme' },
from_email: 'hello@acme.com',
from_name: 'Acme Team'
});
Send to All Contacts (Broadcast)
Send to all active contacts in your database:
// Simple broadcast
await sendmator.email.sendToAll({
template_key: 'newsletter',
variables: {
month: 'March',
year: 2025
}
});
// Scheduled broadcast
await sendmator.email.sendToAll({
template_key: 'announcement',
variables: { feature: 'Dark Mode' },
trigger_at: '2025-03-15T10:00:00Z', // ISO 8601 UTC
from_email: 'news@company.com',
from_name: 'Company News'
});
Send to Contacts with Tags
Target specific segments based on contact tags:
// Single tag
await sendmator.email.sendToTags(['premium'], {
template_key: 'exclusive-offer',
variables: { discount: '20%' }
});
// Multiple tags
await sendmator.email.sendToTags(['premium', 'active'], {
template_key: 'feature-announcement',
variables: { feature: 'Advanced Analytics' }
});
// Scheduled send with custom sender
await sendmator.email.sendToTags(['beta'], {
template_key: 'beta-update',
variables: { version: '2.0' },
from_email: 'beta@company.com',
from_name: 'Beta Team',
trigger_at: '2025-03-10T09:00:00Z'
});
Send to Segment
Send to a dynamic segment (created in Sendmator dashboard):
await sendmator.email.sendToSegment('segment-id-here', {
template_key: 'targeted-campaign',
variables: { campaign: 'Q1 2025' },
from_email: 'marketing@company.com'
});
Advanced Method
For full control over all parameters, use the send() method:
await sendmator.email.send({
// Recipient selection (required)
recipient_type: 'direct_email', // 'direct_email' | 'contact' | 'tag' | 'segment' | 'all'
direct_email: 'user@example.com', // For direct_email
direct_first_name: 'John', // Optional for direct_email
direct_last_name: 'Doe', // Optional for direct_email
// OR for other recipient types:
contact_external_id: 'user-123', // For contact type
tags: ['premium', 'active'], // For tag type
segment_id: 'segment-id', // For segment type
// Content (choose one method)
template_key: 'welcome-email', // Template method
variables: { name: 'John' }, // Template variables
// OR raw content method:
subject: 'Welcome!', // Email subject
content: '<h1>Hello</h1>', // HTML content
plain_text_content: 'Hello', // Plain text fallback
// Optional overrides
from_email: 'hello@acme.com', // Override sender email
from_name: 'Acme Team', // Override sender name
reply_to: 'support@acme.com', // Reply-to address
// Additional options
metadata: { // Custom tracking data
campaign: 'onboarding',
source: 'web'
},
trigger_at: '2025-03-10T10:00:00Z' // Schedule for future
});
Method Comparison
| Method | Use Case | Example |
|---|---|---|
sendTo() | Quick send to email address | Transactional emails, OTPs |
sendToContact() | Send to registered user | Order confirmations, account updates |
sendToAll() | Broadcast to everyone | Newsletters, system announcements |
sendToTags() | Target specific groups | Marketing campaigns, feature rollouts |
sendToSegment() | Dynamic audience targeting | Advanced segmentation |
send() | Full control needed | Complex requirements |
Common Use Cases
1. Welcome Email After Signup
async function sendWelcomeEmail(userEmail: string, userName: string) {
await sendmator.email.sendTo(userEmail, {
template_key: 'welcome-email',
first_name: userName,
variables: {
loginUrl: 'https://app.example.com/login',
supportEmail: 'support@example.com'
},
metadata: {
event: 'user_signup',
timestamp: new Date().toISOString()
}
});
}
2. Order Confirmation
async function sendOrderConfirmation(externalId: string, order: any) {
await sendmator.email.sendToContact(externalId, {
template_key: 'order-confirmation',
variables: {
order_number: order.number,
items: order.items,
total: order.total,
tracking_url: order.trackingUrl
},
metadata: {
order_id: order.id
}
});
}
3. Newsletter Campaign
async function sendNewsletter() {
await sendmator.email.sendToTags(['newsletter', 'active'], {
template_key: 'monthly-newsletter',
variables: {
month: 'March',
year: '2025',
headline: 'New Features Released',
articles: [
{ title: 'Feature 1', url: 'https://...' },
{ title: 'Feature 2', url: 'https://...' }
]
},
from_email: 'newsletter@company.com',
from_name: 'Company Newsletter',
metadata: {
campaign: 'newsletter',
month: '2025-03'
}
});
}
4. Password Reset
async function sendPasswordReset(email: string, resetToken: string) {
const resetUrl = `https://app.example.com/reset-password?token=${resetToken}`;
await sendmator.email.sendTo(email, {
template_key: 'password-reset',
variables: {
reset_url: resetUrl,
expires_in: '1 hour'
},
metadata: {
event: 'password_reset_requested'
}
});
}
5. Scheduled Announcement
async function scheduleAnnouncement() {
const nextWeek = new Date();
nextWeek.setDate(nextWeek.getDate() + 7);
await sendmator.email.sendToAll({
template_key: 'maintenance-announcement',
variables: {
maintenance_date: nextWeek.toDateString(),
duration: '2 hours'
},
trigger_at: nextWeek.toISOString(),
from_email: 'system@company.com',
from_name: 'System Notifications'
});
}
6. Custom HTML Email
async function sendCustomEmail(email: string) {
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
.header { background: #007bff; color: white; padding: 20px; }
.content { padding: 20px; }
</style>
</head>
<body>
<div class="header">
<h1>Custom Email</h1>
</div>
<div class="content">
<p>This is a custom HTML email.</p>
<a href="https://example.com">Click here</a>
</div>
</body>
</html>
`;
await sendmator.email.sendTo(email, {
subject: 'Custom HTML Email',
html: htmlContent,
text: 'This is a custom HTML email. Visit https://example.com',
from_email: 'noreply@example.com',
from_name: 'Example Team'
});
}
Tracking & Status
Get Execution Status
const response = await sendmator.email.sendTo('user@example.com', {
template_key: 'welcome'
});
// Check status later using trigger_id from response
const status = await sendmator.email.getExecutionStatus(response.data.trigger_id);
console.log('Status:', status.data.status);
console.log('Sent at:', status.data.executed_at);
console.log('Recipients:', status.data.recipient_count);
List All Executions
const executions = await sendmator.email.listExecutions({
page: 1,
limit: 20
});
console.log('Total executions:', executions.data.total);
executions.data.executions.forEach(execution => {
console.log(`${execution.template_key} - ${execution.status}`);
});
Error Handling
import { SendmatorError } from '@sendmator/node';
try {
await sendmator.email.sendTo('user@example.com', {
template_key: 'welcome'
});
} catch (error) {
if (error instanceof SendmatorError) {
if (error.statusCode === 404) {
console.error('Template not found');
} else if (error.statusCode === 400) {
console.error('Invalid email data:', error.message);
} else if (error.statusCode === 402) {
console.error('Insufficient wallet balance');
} else {
console.error('Email failed:', error.message);
}
// Access error details
console.error('Error code:', error.code);
console.error('Details:', error.details);
}
}
Best Practices
- Use Simple Methods - Start with
sendTo(),sendToContact(), etc. Only usesend()when you need advanced features - Template-Based Emails - Templates are easier to manage and update than raw HTML
- Provide Plain Text - Always include plain text content for better deliverability
- Personalize with Variables - Use template variables for dynamic content
- Add Metadata - Track campaigns, sources, and events with metadata
- Handle Errors Gracefully - Implement proper error handling for production
- Schedule Strategically - Use
trigger_atfor time-sensitive emails - Set Reply-To - Always provide a reply-to address for customer emails
- Test Before Production - Test with real email addresses first
Configuration Options
sendTo() Options
{
template_key?: string; // Template to use
subject?: string; // Subject (if not using template)
html?: string; // HTML content (if not using template)
text?: string; // Plain text content
first_name?: string; // Recipient first name (optional)
last_name?: string; // Recipient last name (optional)
variables?: Record<string, any>; // Template variables
from_email?: string; // Override sender email
from_name?: string; // Override sender name
reply_to?: string; // Reply-to address
metadata?: Record<string, any>; // Custom tracking data
}
sendToContact() Options
{
template_key: string; // Required
variables?: Record<string, any>;
from_email?: string;
from_name?: string;
reply_to?: string;
metadata?: Record<string, any>;
}
sendToAll() / sendToTags() / sendToSegment() Options
{
template_key: string; // Required
variables?: Record<string, any>;
from_email?: string;
from_name?: string;
reply_to?: string;
metadata?: Record<string, any>;
trigger_at?: string; // ISO 8601 UTC timestamp
}
Recipient Types
| Type | Description | Use Case |
|---|---|---|
| Direct Email | Send to email without creating contact | OTPs, one-time notifications |
| Contact | Send to existing contact by external_id | Personalized transactional emails |
| Tag | Send to contacts with specific tags | Marketing campaigns |
| Segment | Send to dynamically filtered contacts | Advanced targeting |
| All | Send to all active contacts | System-wide announcements |
Scheduling
Schedule emails for future delivery using ISO 8601 UTC timestamps:
// Schedule for specific date/time
await sendmator.email.sendToAll({
template_key: 'weekly-digest',
variables: { week: '12' },
trigger_at: '2025-03-15T10:00:00Z'
});
// Schedule relative to now
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(9, 0, 0, 0);
await sendmator.email.sendToTags(['premium'], {
template_key: 'daily-summary',
trigger_at: tomorrow.toISOString()
});
Response Format
All email send methods return:
{
success: true,
data: {
trigger_id: 'uuid', // Use this to check status later
job_id: 'string', // Internal job ID
message: 'Email queued successfully'
}
}
Next Steps
- SMS SDK - Send SMS messages
- WhatsApp SDK - Send WhatsApp messages
- Contacts SDK - Manage contacts
- OTP SDK - Verify users with OTP
- API Reference - Complete API documentation